File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ---
2+ title : Webpack
3+ stack : Bundler
4+ description : Update webpack to output ES Modules
5+ ---
6+
7+ webpack is one of the early bundlers for the JavaScript ecosystem. Currently, support for ESM-format outputs is still under ` experiments `
8+
9+ ## 1. Mark the package as ESM
10+
11+ Add ` type: "module" ` to your ` package.json ` . Every ` .js ` file in the package is
12+ now treated as an ES module.
13+
14+ ``` json
15+ {
16+ "name" : " my-package" ,
17+ "type" : " module"
18+ }
19+ ```
20+
21+ Any file that genuinely still has to be CommonJS (for example, a legacy config
22+ file for another tool) can keep the ` .cjs ` extension.
23+
24+ ## 2. Emit a single ESM bundle
25+
26+ In webpack 5, enable module output and set the library to ` module ` :
27+
28+ ``` js
29+ export default {
30+ mode: ' production' ,
31+ entry: ' ./src/index.js' ,
32+ experiments: {
33+ outputModule: true
34+ },
35+ output: {
36+ filename: ' index.js' ,
37+ module: true ,
38+ library: {
39+ type: ' module'
40+ },
41+ chunkFormat: ' module'
42+ }
43+ };
44+ ```
45+
46+ If you had a separate CommonJS build, remove it and keep just the ESM output.
47+ For config files that must stay CommonJS, rename them to ` .cjs ` instead of ` .js ` .
48+
49+ ## 3. Point ` exports ` at the bundle
50+
51+ Replace ` main ` with an ` exports ` field. This is what lets Node.js and bundlers
52+ resolve your package, and it stops deep imports into your ` dist ` folder from
53+ becoming part of your public API by accident.
54+
55+ ``` json
56+ {
57+ "exports" : {
58+ "." : " ./dist/index.js"
59+ },
60+ "files" : [" dist" ]
61+ }
62+ ```
63+
64+ ## 4. Check the result
65+
66+ Run [ publint] ( https://publint.dev ) to catch problems with leftover CommonJS
67+ references, publishing config, and other package metadata issues.
68+
69+ ``` sh
70+ npx publint
71+ ```
You can’t perform that action at this time.
0 commit comments