Skip to content

Commit 05925c2

Browse files
chenxsanmontogeekjamesgeorge007
authored
docs(migrate): improve webpack 5 migration guide (#4382)
* docs(migrate): improve webpack 5 migration guide * Update src/content/migrate/5.md Co-authored-by: Fernando Montoya <[email protected]> * Update src/content/migrate/5.md * Apply suggestions from code review Co-authored-by: James George <[email protected]> Co-authored-by: Fernando Montoya <[email protected]> Co-authored-by: James George <[email protected]>
1 parent d6f602c commit 05925c2

File tree

1 file changed

+102
-80
lines changed
  • src/content/migrate

1 file changed

+102
-80
lines changed

src/content/migrate/5.md

Lines changed: 102 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -16,68 +16,55 @@ This guide aims to help you migrating to webpack 5 when using webpack directly.
1616

1717
## Preparations
1818

19-
webpack 5 requires at least Node.js 10.13.0 (LTS).
19+
Webpack 5 requires at least Node.js 10.13.0 (LTS), so make sure you upgrade your Node.js if you're still running an older one.
2020

21-
T> Using newer Node.js version can improve build performance.
21+
## Upgrade webpack 4 and its plugins/loaders
2222

23-
### Upgrade webpack and its dependencies
23+
1. Upgrade `webpack` 4 to the latest available version.
2424

25-
#### Upgrade webpack 4 to the latest available version
26-
27-
When using webpack >= 4, upgrading to the latest webpack 4 version should not require additional guidance.
28-
If you are using webpack version less than 4 please see the [webpack 4 migration guide](/migrate/4/).
29-
30-
#### Upgrade webpack-cli to the latest available version (when used)
31-
32-
#### Upgrade all used Plugins and Loaders to the latest available version
25+
- When using webpack >= 4, upgrading to the latest webpack 4 version should not require additional guidance.
26+
27+
- If you are using webpack version less than 4 please see the [webpack 4 migration guide](/migrate/4/).
3328

34-
Some Plugins and Loaders might have a beta version that has to be used in order to be compatible with webpack 5.
29+
2. Upgrade `webpack-cli` to the latest available version (when used)
3530

36-
W> Check related Plugins and Loaders migration guide when upgrading across major versions. Several commonly-used loaders like `raw-loader`, `url-loader`, and `file-loader` should be replaced using the new built-in [Asset Modules](/guides/asset-modules/) feature.
31+
3. Upgrade all used Plugins and Loaders to the latest available version
3732

38-
W> ExtendedAPIPlugin is removed and the logic is merged into [`APIPlugin`](https://github.com/webpack/webpack/blob/master/lib/APIPlugin.js).
33+
Some Plugins and Loaders might have a beta version that has to be used in order to be compatible with webpack 5.
3934

40-
#### Make sure your build has no errors or warnings
35+
### Make sure your build has no errors or warnings
4136

42-
There might be new errors or warnings because of the upgraded versions of webpack, webpack-cli, Plugins and Loaders. Keep an eye for deprecation warnings during the build.
37+
There might be new errors or warnings because of the upgraded versions of `webpack`, `webpack-cli`, Plugins and Loaders. Keep an eye for deprecation warnings during the build.
4338

44-
You can invoke webpack this way to get stack traces for deprecation warnings to figure out which Plugins and Loaders are responsible.
39+
You can invoke `webpack` this way to get stack traces for deprecation warnings to figure out which Plugins and Loaders are responsible.
4540

4641
```bash
4742
node --trace-deprecation node_modules/webpack/bin/webpack.js
4843
```
4944

50-
W> webpack 5 removes all deprecated features. In order to proceed, there should be no webpack deprecation warnings during the build.
51-
52-
#### Make sure you are using entry point information from stats
45+
As webpack 5 removes all deprecated features, make sure there's no webpack deprecation warnings during the build in order to proceed.
5346

54-
T> If you are using [HtmlWebpackPlugin](/plugins/html-webpack-plugin/) skip this step.
47+
### Make sure to use `mode`
5548

56-
When using static HTML or creating HTML in other way, make sure to use entry points from stats JSON to generate `<script>`, `<style>` and `<link>` tags.
49+
Set `mode` to either [`production`](/configuration/mode/#mode-production) or [`development`](/configuration/mode/#mode-development) to make sure that corresponding defaults are set.
5750

58-
If this is not possible, avoid setting `splitChunks.chunks: 'all'` and `splitChunks.maxSize` later in this guide. Note that this is sub-optimal and a workaround.
59-
60-
#### Make sure to use `mode`
61-
62-
Set mode to either [`production`](/configuration/mode/#mode-production) or [`development`](/configuration/mode/#mode-development) to make sure that corresponding defaults are set.
63-
64-
#### Update outdated options
51+
### Update outdated options
6552

6653
Update the following options to their new version (if used):
6754

68-
- `optimization.hashedModuleIds: true` `optimization.moduleIds: 'deterministic'`
69-
- `optimization.namedChunks: true` `optimization.chunkIds: 'named'`
70-
- `optimization.namedModules: true` `optimization.moduleIds: 'named'`
71-
- `NamedModulesPlugin` `optimization.moduleIds: 'named'`
72-
- `NamedChunksPlugin` `optimization.chunkIds: 'named'`
73-
- `HashedModuleIdsPlugin` `optimization.moduleIds: 'deterministic'`
74-
- `optimization.noEmitOnErrors: false` `optimization.emitOnErrors: true`
75-
- `optimization.occurrenceOrder: true` `optimization: { chunkIds: 'total-size', moduleIds: 'size' }`
76-
- `optimization.splitChunks.cacheGroups.vendors` `optimization.splitChunks.cacheGroups.defaultVendors`
77-
- `Compilation.entries` `Compilation.entryDependencies`
78-
- `serve` `serve` is removed in favor of [`DevServer`](/configuration/dev-server/)
55+
- `optimization.hashedModuleIds: true` `optimization.moduleIds: 'deterministic'`
56+
- `optimization.namedChunks: true` `optimization.chunkIds: 'named'`
57+
- `optimization.namedModules: true` `optimization.moduleIds: 'named'`
58+
- `NamedModulesPlugin` `optimization.moduleIds: 'named'`
59+
- `NamedChunksPlugin` `optimization.chunkIds: 'named'`
60+
- `HashedModuleIdsPlugin` `optimization.moduleIds: 'deterministic'`
61+
- `optimization.noEmitOnErrors: false` `optimization.emitOnErrors: true`
62+
- `optimization.occurrenceOrder: true` `optimization: { chunkIds: 'total-size', moduleIds: 'size' }`
63+
- `optimization.splitChunks.cacheGroups.vendors` `optimization.splitChunks.cacheGroups.defaultVendors`
64+
- `Compilation.entries` `Compilation.entryDependencies`
65+
- `serve` `serve` is removed in favor of [`DevServer`](/configuration/dev-server/)
7966

80-
#### Test webpack 5 compatibility
67+
### Test webpack 5 compatibility
8168

8269
Try to set the following options in your webpack 4 configuration and check if build still works correctly.
8370

@@ -91,25 +78,27 @@ module.exports = {
9178
};
9279
```
9380

81+
You have to remove these options again when upgrading your configuration for webpack 5.
82+
9483
T> webpack 5 removes these options from the configuration schema and will always use `false`.
9584

96-
You have to remove these options again when upgrading your configuration for webpack 5.
85+
## Upgrade webpack to 5
9786

98-
#### Upgrade webpack version
87+
Now let's upgrade webpack to version 5:
9988

100-
npm: `npm install webpack@latest --dev`
89+
- npm: `npm install webpack@latest --dev`
10190

102-
Yarn: `yarn add webpack@latest -D`
91+
- Yarn: `yarn add webpack@latest -D`
10392

104-
#### Clean up configuration
93+
### Clean up configuration
10594

10695
- Consider removing `optimization.moduleIds` and `optimization.chunkIds` from your webpack configuration. The defaults could be better, because they support long term caching in [`production mode`](/configuration/mode/#mode-production) and debugging in [`development` mode](/configuration/mode/#mode-development).
10796
- When using `[hash]` placeholder in webpack configuration, consider changing it to `[contenthash]`. It is not the same, but proven to be more effective.
10897
- If you are using Yarn's PnP and the `pnp-webpack-plugin`, we have good news: it is supported by default now. You have to remove it from the configuration.
10998
- If you are using `IgnorePlugin` with a regular expression as argument, it takes an `options` object now: `new IgnorePlugin({ resourceRegExp: /regExp/ })`.
110-
- If you are using `node.something: 'empty'` replace it with `resolve.fallback.something: false`.
99+
- If you are using something like `node.fs: 'empty'` replace it with `resolve.fallback.fs: false`.
111100
- If you are using `watch: true` in webpack Node.js API, remove it. There's no need to set it as it's indicated by the compiler method you call, either `true` for `watch()` or `false` for `run()`.
112-
- If you have `rules` defined for loading assets using `raw-loader`, `url-loader`, or `file-loader`, these should be configured as [Asset Modules](/guides/asset-modules/) instead.
101+
- If you have `rules` defined for loading assets using `raw-loader`, `url-loader`, or `file-loader`, please use [Asset Modules](/guides/asset-modules/) instead as they're going to be deprecated in near future.
113102
- If you have `target` set to a function, update it to `false` and apply that function within `plugins` option. See example below:
114103

115104
```json
@@ -144,58 +133,95 @@ Consider removing defaults:
144133
- Using `output.path: path.resolve(__dirname, 'dist')`: you can omit it, that's the default.
145134
- Using `output.filename: '[name].js'`: you can omit it, that's the default.
146135

147-
Need to support an older browser?
136+
### Need to support an older browser like IE 11?
148137

149-
- By default, webpack will use your browserslist config to decide which code style to emit.
150-
- Without a browserslist it would emit ES6 style. You can use `target: ["web", "es5"]` to change it to ES5.
138+
- By default, webpack 5 will use your `browserslist` config to decide which code style to emit for the runtime code.
139+
- Without a `browserslist` webpack's runtime code uses ES2015 syntax (e.g., arrow function) to build smaller bundles. If your build targets environments that don't support ES2015 syntax (like IE11), you'll need to set `target: ['web', 'es5']` to use ES5 syntax.
151140
- For Node.js, builds include the supported Node.js version in the `target` option and webpack will automatically figure out which syntax is supported, e.g. `target: 'node8.6'`.
152141

153-
#### Cleanup the code
142+
### Cleanup the code
143+
144+
#### Using `/* webpackChunkName: '...' */`
154145

155-
Using `/* webpackChunkName: '...' */`: Make sure to understand the intention:
146+
Make sure to understand the intention:
156147

157148
- The chunk's name here is intended to be public.
158149
- It's not a development-only name.
159-
- webpack will use it to name files in production and development modes.
160-
- webpack 5 will automatically assign useful file names in `development` mode even when not using `webpackChunkName`.
150+
- Webpack will use it to name files in production and development modes.
151+
- Webpack 5 will automatically assign useful file names in `development` mode even when not using `webpackChunkName`.
152+
153+
#### Using named exports from JSON modules
154+
155+
This is not supported by the new specification and you will get a warning. Instead of:
161156

162-
Using named exports from JSON modules: this is not supported by the new specification and you will get a warning. Instead of `import { version } from './package.json'; console.log(version);` use `import package from './package.json'; console.log(package.version);`
157+
```js
158+
import { version } from './package.json';
159+
console.log(version);
160+
```
161+
162+
use:
163+
164+
```js
165+
import pkg from './package.json';
166+
console.log(pkg.version);
167+
```
163168

164169
#### Cleanup the build code
165170

166171
- When using `const compiler = webpack(...);`, make sure to close the compiler after using it: `compiler.close(callback);`.
167172
- This doesn't apply to the `webpack(..., callback)` form which automatically closes.
168173
- This is optional if you use webpack in watching mode until the user ends the process. The idle phases in watch mode will be used for this kind of work.
169174

170-
#### Run a single build and follow advises
175+
### Run a single build and follow advises
171176

172-
Please make sure to read errors/warnings carefully.
177+
Please make sure to read the building errors/warnings carefully. If there is no corresponding advise, please create an issue and we will try to resolve it.
173178

174-
If there is no corresponding advise? Please create an issue and we will try to resolve it. Repeat this step until you solved at least level 3 or 4:
179+
Repeat the following steps until you solved at least level 3 or 4:
175180

176-
- Level 1: Schema validation fails. Configuration options have changed. There should be a validation error with a `BREAKING CHANGE:` note, or a hint which option should be used instead.
177-
- Level 2: webpack exits with an error. The error message should tell you what needs to be changed.
178-
- Level 3: Build Errors. The error message should have a `BREAKING CHANGE:` note.
179-
- Level 4: Build Warnings. The warning message should tell you what can be improved.
180-
- Level 5: Runtime Errors. This is tricky. You probably have to debug to find the problem. A general advise is difficult here.
181-
- Level 6: Deprecation Warnings. You probably get a lot of deprecation warnings. This is not directly a problem. Plugins need time to catch up with core changes. Please report these deprecations to the plugins. These deprecations are only warnings and the build will still work with only minor drawbacks (like less performance).
182-
- Level 7: Performance issues. Usually performance should improve with webpack 5, but there are also a few cases where performance get worse.
181+
- Level 1: __Schema validation fails__.
182+
183+
Configuration options have changed. There should be a validation error with a `BREAKING CHANGE:` note, or a hint of which option should be used instead.
184+
185+
- Level 2: __Webpack exits with an error__.
186+
187+
The error message should tell you what needs to be changed.
188+
189+
- Level 3: __Build Errors__.
190+
191+
The error message should have a `BREAKING CHANGE:` note.
192+
193+
- Level 4: __Build Warnings__.
194+
195+
The warning message should tell you what can be improved.
196+
197+
- Level 5: __Runtime Errors__.
198+
199+
This is tricky. You probably have to debug to find the problem. A general advise is difficult here. But we do list some common advices below regarding Runtime Errors:
183200

184-
- Regarding Runtime Errors:
185201
- `process` is not defined.
186202
- webpack 5 does no longer include a polyfill for this Node.js variable. Avoid using it in the frontend code.
187-
- Want to support frontend and browser usage? Use the `exports` or `imports` package.json field to use different code depending on the environment.
188-
- Also use the `browser` field to support older bundlers,.
203+
- Want to support browser usage? Use the `exports` or `imports` package.json field to use different code depending on the environment.
204+
- Also use the `browser` field to support older bundlers.
189205
- Alternative: Wrap code blocks with the `typeof process` checks. Note that this will have a negative impact on the bundle size.
190206
- Want to use environment variables with `process.env.VARIABLE`? You need to use the `DefinePlugin` or `EnvironmentPlugin` to define these variables in the configuration.
191207
- Consider using `VARIABLE` instead and make sure to check `typeof VARIABLE !== 'undefined'` too. `process.env` is Node.js specific and should be avoided in frontend code.
192208
- 404 errors pointing to URLs containing `auto`
193209
- Not all ecosystem tooling is ready for the new default automatic `publicPath` via `output.publicPath: "auto"`
194210
- Use a static `output.publicPath: ""` instead.
195-
- Regarding Deprecation Warnings:
211+
212+
- Level 6: __Deprecation Warnings__.
213+
214+
You probably get a lot of deprecation warnings. This is not directly a problem. Plugins need time to catch up with core changes. Please report these deprecations to the plugins. These deprecations are only warnings and the build will still work with only minor drawbacks (like less performance).
215+
196216
- You can hide deprecation warnings by running node with `--no-deprecation` flag, e.g.: `node --no-deprecation node_modules/webpack/bin/webpack.js`. This should only be a temporary workaround.
197217
- Plugins and Loaders contributors can follow the advises in the deprecation messages to improve the code.
198-
- Regarding Performance issues:
218+
219+
- Level 7: __Performance issues__.
220+
221+
Usually, performance should improve with webpack 5, but there are also a few cases where performance gets worse.
222+
223+
And here are something you can do to improve the situation:
224+
199225
- Profile where the time is spend.
200226
- `--profile --progress` displays a simple performance profile now
201227
- `node --inspect-brk node_modules/webpack/bin/webpack.js` + [`chrome://inspect`](chrome://inspect) / [`edge://inspect`](edge://inspect) (see profiler tab).
@@ -212,21 +238,17 @@ If there is no corresponding advise? Please create an issue and we will try to r
212238
- Persistent Caching can help to improve the repetitive full builds.
213239
- Module Federation allows to split the application into multiple smaller builds.
214240

215-
#### Turn off ES2015 syntax in runtime code, if necessary
216-
217-
By default, webpack's runtime code uses ES2015 syntax to build smaller bundles. If your build targets environments that don't support this syntax (like IE11), you'll need to set `target: ['web', 'es5']` to revert to ES5 syntax (`'web'` if target environment is browser).
218-
219-
#### Everything works?
241+
## Everything works?
220242

221243
Please tweet that you have successfully migrated to webpack 5. [Tweet it](https://twitter.com/intent/tweet?source=https://webpack.js.org/migrate/5/&text=I%20just%20migrated%20to%20webpack%205%20using%20its%20migration%20guide!%20&via=webpack&hashtags=webpack,webpack5)
222244

223-
#### It is not working?
245+
## It is not working?
224246

225247
Create an [issue](https://github.com/webpack/webpack/issues/new?template=Bug_report.md) and tell us about the issues you have encountered during the migration.
226248

227-
#### Something missing in this guide?
249+
## Something missing in this guide?
228250

229-
Please open a Pull Request to help the next person using this guide.
251+
Please open a [Pull Request](https://github.com/webpack/webpack.js.org/edit/master/src/content/migrate/5.md) to help the next person using this guide.
230252

231253
## Changes to internals
232254

@@ -239,6 +261,6 @@ The changes to webpack internals such as: adding types, refactoring code and met
239261
webpack 5 ships with built-in [`this.getOptions`](/api/loaders/#thisgetoptionsschema) method available in loader context. This is a breaking change for loaders that had been using `getOptions` method from previously preferred [schema-utils](https://github.com/webpack/schema-utils):
240262

241263
- `this.getOptions` is available since webpack 5
242-
- Instead of JSON5 it supports JSON as a query string: `?{arg:true}` `?{"arg":true}`. Using JSON5 should be considered and documented as deprecated in favor of JSON in respective Loader's documentation.
264+
- Instead of JSON5 it supports JSON as a query string: `?{arg:true}` `?{"arg":true}`. Using JSON5 should be considered and documented as deprecated in favor of JSON in the respective Loader's documentation.
243265
- [`loader-utils`](https://github.com/webpack/loader-utils) has specific behavior for parsing query strings (`true`, `false` and `null` won't be parsed as `string` but as a primitive value). This is no longer the case for the new built-in `this.getOptions` method, which uses native [`querystring`](https://nodejs.org/api/querystring.html) parsing (ships with Node.js). It is still possible to add custom behavior for these cases in the Loader's code after getting the options by using `this.getOptions` method.
244266
- Schema argument is optional for the new `this.getOptions` method, but we strongly advise to add schema validation for your Loader's options. The `title` field in the schema, can be used to customize the validation error message e.g. `"title": "My Loader ooooptions"` will result in displaying errors this way: `Invalid ooooptions object. My Loader has been initialised using an ooooptions object that does not match the API schema. - ooooptions.foo.bar.baz should be a string.`

0 commit comments

Comments
 (0)