Run your javascript code on the fly

Gao

Summary

It has been eight years since es2015 modules were released. After so many years, with the advancement of technology, each operating environment can already support running es module directly.

Here is the ways

Server side node.js

deno.land support es modules since it's first release.

node.js support es modules since 16 LTS

Add type: module in package.json

// ./node_modules/pkg/package.json { "type": "module", "exports": { "import": "./wrapper.mjs", "require": "./index.cjs" } }

In browser

All modern browsers already support es modules.

Just add type=module on script tag.

<script src="./index.js" type=module></script>

Using CDN to import script in browser.

esm.sh

esm.sh transforms any npm modules automatically into ES Modules. So you can try any npm module with the url like https://esm.sh/<npm-module-name> e.g. https://esm.sh/react. It also serves type declaration through X-TypeScript-Types header. So you can even type check the exported APIs when the CDN find types.

esm.sh also provides the Node.js polyfill for Deno if the user agent is Deno.

You can load modules like React, React Router, styled-components, twind, etc.

import React from "https://esm.sh/react"; import ReactDOM from "https://esm.sh/react-dom"; import { BrowserRouter, Link, Route } from "https://esm.sh/react-router"; import styled from "https://esm.sh/styled-components"; import { tw } from "https://esm.sh/twind";

Skypack

Skypack is very similar to esm.sh. It automatically converts npm modules into ES Modules. It provides types via X-TypeScript-Types. So you can type check the exported APIs. Skypack also provides Node.js native API polyfills for Deno.

import React from "https://cdn.skypack.dev/react"; import ReactDOM from "https://cdn.skypack.dev/react-dom"; import styled from "https://cdn.skypack.dev/styled-components"; import { tw } from "https://cdn.skypack.dev/twind";

unpkg.com

unpkg.com provides the npm modules as is. Many npm modules often provides UMD (Universal Module Definition) format of the module, or ES Module version of the module, like d3.js and threejs.

In Browsers alias

There is no standard for this yet, but one is under way (Github repo here.) With that proposal, you'd have a script with type="importmap" that listed the aliases, like this:

<script type="importmap"> { "imports": { "react": "../vendors.react.js", "react-dom": "https://some.cdn/react-dom.min.js" } } </script>

Note that relative paths are relative to the document in which this script appears, not the module where you use the alias.

Chrome trialed this starting in v74, it's behind a flag you have to enable: chrome://flags/#enable-experimental-productivity-features. The Chrome platform status page for it lists "no public signals" from other vendors (so far).

At last

By the way, if you import from cdn, it will break the CSP rules purpose.