Skip to content

Instantly share code, notes, and snippets.

@rumkin
Last active May 21, 2020 13:59
Show Gist options
  • Save rumkin/0f2e14f84c81ed5aae6beac7593a78d9 to your computer and use it in GitHub Desktop.
Save rumkin/0f2e14f84c81ed5aae6beac7593a78d9 to your computer and use it in GitHub Desktop.
Top-level modules

Top Level Modules

When Node.js or a browser imports top-level modules they usually executes top-level code.

Package.json

{
  "exports": {
    "import": "./index.js"
  },
  "execute": {
    "browser": "browser",
    "node": "node"
  }
}

index.js

export function browser() {
  console.log("Hello, Browser!")
}

export function node() {
  console.log("Hello, Node!")
}

Usage

$ node .
Hello, Node!
<script src="." type="module" />

Outputs to console

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