importmaps
Note
There is another module that provides similar functionality to this: Importmap module.
Features it includes above this module:
- Support for scoped imports (scopes key in the importmap JSON)
- Invalidating browser cache when the JS files are upadted (similar to what core does)
- Optionally generate
tags for modules in the importmap (this can help the browser parallelize requests, especially with long import chains)
It is hoped there will be a solution for this in Drupal core from 10.3 - please see the core issue.
If using this module please be aware that the API for this in core will likely be different.
Introduction
Provides an API for Import maps in Drupal.
Import maps allow you to bundle your JavaScript and exclude third-party dependencies, leaving them as naked imports.
e.g.
import React from 'react';
Ordinarily the browser can't understand that.
With an import map it can.
You can only have one <script type="importmap"></script> in the page, and that's where this module comes in.
Features
Adds a <script type="importmap"> element to the page.
Allows modules to declare how to resolve (import) modules.
Post-Installation
If you need to provide an import map, add a yourmodule.importmaps.yml file to the root of your module.
It should look like this
someRelativeEsModule:
path: relative/path/to/your/file.js
someAbsoluteEsModule:
path: /some/path/from/the/drupal/root/to/your/file.js
This would then allow your bundled code to look like so
import Something from "someRelativeEsModule"
import AnotherThing from "someAbsoluteEsModule"
Recommended modules/libraries
The React module makes use of this functionality.
A note on bundling
If you want to make use of importmaps, you probably want to use something like Vite/Rollup externals e,g
// vite.config.ts
defineConfig({
// other stuff
build: {
rollupOptions: {
external: ["react", "react-dom", "react/jsx-runtime"],
},
},
// more other stuff
})
Webpack has a similar functionality