Skip to content

Commit ea5d016

Browse files
donecarlo43081j
andauthored
chore: add webpack guides (#4)
* chore: add webpack guides * chore: formatting * Update guides/webpack.md Co-authored-by: James Garbutt <43081j@users.noreply.github.com> --------- Co-authored-by: James Garbutt <43081j@users.noreply.github.com>
1 parent 015eee2 commit ea5d016

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

‎guides/webpack.md‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
```

0 commit comments

Comments
 (0)