-
Create a new Node package (an empty folder with a
package.json
will do), and set"type": "module"
in it. -
Create an
index.js
file with this content:export function amaze() { console.log("modules importing themselves? wow"); } import { amaze as wow } from './index.js'; wow();
-
Invoke it by running
node index.js
. It will work just fine and log the string. -
Notice that module imports and exports are static, and get handled before any of the actual class body runs. So you can import from yourself at the top of a module, but any initialization will not have happened yet:
import { amaze as wow, neat as cool } from './index.js'; wow(); // works, but only because `function`s are hoisted console.log(cool); // 💥 "ReferenceError: Cannot access 'wow' before initialization" export function amaze() { console.log("modules importing themselves? wow"); } export const neat = "totally neat";
In other words, it works exactly like if you tried to do
console.log(neat)
at the same point in the file.
Last active
November 24, 2021 16:16
-
-
Save chriskrycho/dc5adabd80c04d405c7a4894c0ffb99e to your computer and use it in GitHub Desktop.
self-recursive ES modules 🤯
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment