Skip to content

Instantly share code, notes, and snippets.

@chriskrycho
Last active November 24, 2021 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriskrycho/dc5adabd80c04d405c7a4894c0ffb99e to your computer and use it in GitHub Desktop.
Save chriskrycho/dc5adabd80c04d405c7a4894c0ffb99e to your computer and use it in GitHub Desktop.
self-recursive ES modules 🤯
  1. Create a new Node package (an empty folder with a package.json will do), and set "type": "module" in it.

  2. 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();
  3. Invoke it by running node index.js. It will work just fine and log the string.

  4. 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.

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