Skip to content

Instantly share code, notes, and snippets.

@evisong
Last active May 26, 2022 09:34
Show Gist options
  • Select an option

  • Save evisong/0e70d3ee5215d751e7d57d8378de9c96 to your computer and use it in GitHub Desktop.

Select an option

Save evisong/0e70d3ee5215d751e7d57d8378de9c96 to your computer and use it in GitHub Desktop.
ESM self import: different behaviors between browser native and es-module-shims
export const b = {
m: () => console.log('Run m')
};
import { b as c } from './module-self-import.mjs';
const m = c.m;
export default function a() {
console.log('Run a');
m();
}
<!DOCTYPE html>
<html>
<body>
<script type="module">
import a from './module-self-import.mjs';
console.log('Run inline');
a();
</script>
</body>
</html>
{
"name": "self-import",
"version": "1.0.0",
"private": true,
"description": "",
"main": "index.js",
"scripts": {
"start": "serve -C"
},
"author": "",
"license": "ISC",
"devDependencies": {
"serve": "^13.0.2"
}
}
<!DOCTYPE html>
<html>
<head>
<script async src="https://ga.jspm.io/npm:es-module-shims@1.5.5/dist/es-module-shims.js"></script>
</head>
<body>
<script type="module-shim">
import a from './module-self-import.mjs';
console.log('Run inline');
a();
</script>
</body>
</html>
@evisong
Copy link
Author

evisong commented May 26, 2022

Download and run:

npm install
npm start

Visit http://localhost:3000/native.html or http://localhost:3000/shims.html in browser.

For native.html, the browser console shows:

Run inline
Run a
Run m

For shims.html, the browser console shows:

module.mjs:7 Uncaught TypeError: Cannot read properties of undefined (reading 'm')
    at module.mjs:7:13

FYI, a similar self-import pattern in module-self-import.mjs can be found in Webpack 5 generated ESM bundles (with code-splitting).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment