Feature detection for modules (ESM) + dynamic imports.
npm i -S @substrate-system/esm
Dynamic imports?
function esm ():boolean
Is importmap
supported?
function importMap ():boolean
Create script tags in the document, and wait for them to load.
async function umd (...files:string[]):Promise<void>
import {
importMap,
esm,
umd
} from '@substrate-system/esm'
require('@substrate-system/esm')
Copy the minified files to a location that is accessible to your web server, then link to them in HTML.
cp ./node_modules/@substrate-system/esm/dist/index.min.js ./public/esm.min.js
<script type="module" src="./esm.min.js"></script>
You will need to add unsafe-eval
to your CSP.
script-src 'self' 'unsafe-eval';
Note
This would be for a script built with a "global name" of test
,
e.g. --global-name=test
. The name you access on globalThis
depends on your
build process.
import { importMap, esm, umd } from '@substrate-system/esm'
const importMapOk = importMap()
const dynamic = esm()
if (dynamic) {
const { hello } = await import('/test.js')
hello()
} else {
// load a UMD script
await umd('/test.umd.js')
// now we have a global variable
hello = globalThis.test.hello
hello()
}
If you need to support both newer platforms, and also platforms without ES modules, then build a UMD version in addition to building modules.
Note
The argument --external:"./test.js"
In your top-level module, build it with the relevant dependencies excluded, not bundled.
esbuild ./test/index.ts --external:"./test.js" --format=iife --bundle --keep-names > public/bundle.js
Note
The --global-name
argument
Given the example above, you would want to build your dependency module
as an IIFE
function, attached to window
at .test
, in addition to building
it as a normal ESM module.
esbuild ./src/test.ts --global-name=test --format=iife --bundle --keep-names > public/test.umd.js
Three commands:
Build the file, and start a server:
npm start
Build the files in iife
format, and start a server:
npm run start:iife
Build in 2016
compatibility mode:
npm run start:2016
Development is a little bit janky because there is not an easy way to start an old version of a browser.
That's why, in the iife and 2016
versions, we do an extra check, besides
looking at esm()
.