Skip to content

substrate-system/esm

Repository files navigation

esm

GitHub Pages deploy semantic versioning types module Common Changelog GZip size install size dependencies license

Feature detection for modules (ESM) + dynamic imports.

Contents

Install

npm i -S @substrate-system/esm

API

ES Modules

Dynamic imports?

function esm ():boolean

importMap

Is importmap supported?

function importMap ():boolean

umd(...files:string[])

Create script tags in the document, and wait for them to load.

async function umd (...files:string[]):Promise<void>

Use

ESM + Bundler

import {
    importMap,
    esm,
    umd
} from '@substrate-system/esm'

Common JS

require('@substrate-system/esm')

pre-built JS

Copy the minified files to a location that is accessible to your web server, then link to them in HTML.

copy

cp ./node_modules/@substrate-system/esm/dist/index.min.js ./public/esm.min.js

HTML

<script type="module" src="./esm.min.js"></script>

CSP

You will need to add unsafe-eval to your CSP.

script-src 'self' 'unsafe-eval';

Example

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()
}

Build

If you need to support both newer platforms, and also platforms without ES modules, then build a UMD version in addition to building modules.

Application code

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

Dependencies

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

develop

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().

About

Feature detection for modules

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •