Skip to content

Instantly share code, notes, and snippets.

@robin-a-meade
Last active November 15, 2022 09:53
Show Gist options
  • Save robin-a-meade/6d1a94b39f085fcece0318863a2f0a75 to your computer and use it in GitHub Desktop.
Save robin-a-meade/6d1a94b39f085fcece0318863a2f0a75 to your computer and use it in GitHub Desktop.
Webpack detects ESM modules automatically
/main.js
/node_modules
/package-lock.json

Webpack detects ESM modules automatically

Read the documentation

https://webpack.js.org/guides/ecma-script-modules/

Takeaways:

  • WebPack automatically detects the modules system being used
  • But you are still free to use the Node.js way of explicitly specifying the module type through the following mechanisms:
    • Add "type": "module" to package.json to force all files below to be considered ECMAScript modules.
    • Add "type": "commonjs" to package.json to force all files below to be considered CommonJS modules.
    • Use .mjs extension to force them to be ESM modules
    • Use .cjs extension to force them to be CommonJS modules

Run this example

  1. Create a temporary directory and cd into it
  2. Clone the gist
  3. Run the webpack build
cd "$(mktemp -d)"
git clone [email protected]:6d1a94b39f085fcece0318863a2f0a75.git .
npm install
npm run build
firefox index.html

Open your browser's developer tools and look at the console output. You should see "Hello, World!"

Closing thoughts

Webpack makes it easy to use ESM modules.

  • We didn't need to add babel to our project to transpile ESM modules to CommonJS modules.
  • We didn't need to change the file extensions from .js to .mjs.
  • We didn't need to add "type": "module" to package.json.
export default function hello() { console.log("Hello, World!"); }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World! Site Title</title>
</head>
<body>
<h1>Hello World!</h1>
<script src="main.js"></script>
</body>
</html>
import f from "./hello.js";
f();
{
"name": "blahblah",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode development --entry ./index.js -o ."
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment