Webpack 5 Release (2020-10-10)
Webpack 4 was released in February 2018. Since then we’ve encapsulated a number of features, but haven’t introduced any disruptive changes. We know that people don’t like breaking changes. Especially with tools like WebPack, people only get a limited amount of exposure to this application for a year and leave it behind the rest of the time as long as it works. But there is a price to pay for not introducing new features without breaking them: no core API or architecture level updates. Over time, there comes a point where the problems pile up to the point where we need to fix them by introducing disruptive changes rather than making the code more unmaintainable. Now it’s time for a new release, and WebPack 5 includes architectural upgrades and new features that we can implement without introducing disruptive changes. At the same time, a big release is an opportunity to correct some errors and be in line with industry proposals and specifications. So today (202-10-10) WebPack 5 is officially released, but that doesn’t mean the release is complete, bug-free, and all feature development is completed. In the meantime, we’ll continue to maintain WebPack 4, fix bugs and add new features. In the coming days we will focus on bug fixes and feature additions will come later.
Q&A
What does a distribution mean?
This means that we have completed the development of disruptive changes. A lot of top-level refactoring has been done, and a good foundation has been laid for future features, including current ones.
When is the right time to upgrade?
It depends. The upgrade will most likely not work the first time, and you may need to try it twice or even three times. If you are not sensitive to this process, you are welcome to upgrade immediately and provide feedback to Webpack, plug-ins, Loaders, etc. We’re very keen to fix that. Some of them have already been fixed, and you may be one of those who have benefited from feedback from others.
Sponsored by the update
Webpack is entirely supported by sponsorship. It has nothing to do with big companies like open source projects. 99% of sponsorships are paid to contributors and maintainers of WebPack code based on the size of their contribution. We firmly believe that this investment will make WebPack even better. Webpack is suffering (as many companies and people are) from the negative impact of the pandemic, which has reduced corporate sponsorship of open source projects. We can’t afford to pay contributors as much as they should, but with only half the funding available, we have to make cuts. Until things get better, we only pay contributors or maintainers for submitting code in the first 10 days of the month. The rest of the time they do volunteer work, paid by their original employer, or earn money by doing other things. This means that the first 10 days we paid were much more than the time the developers spent. Most sincere thanks go out to Trivago for their sponsorship of Webpack over the past three years. Regrettably, they were unable to continue their sponsorship this year as they were themselves affected by novel Coronavirus. I hope other companies are as generous as they are. Thanks to all sponsors!
General direction
The changes in this release focus on the following directions:
- Build performance through persistent caching
- Improve long-term caching with better algorithms and default Settings
- Use the Web platform to improve compatibility
- To clean up some of the internal legacy structure, the V4 release introduced some weird states to implement some features, and there are no disruptive changes introduced here
- Some disruptive changes are referenced here for future features, which allowed us to stay with the V5 release long enough
Migration guide
Click on migration Guide for details
Removal of major changes
Remove obsolete configuration items
All deprecated items in V4 have been removed. Migration: Make sure your WebPack 4 package does not print any alerts about deprecated apis. Here are some items that have been removed, but there are no deprecated API alerts in V4:
- IgnorePlugin and BannerPlugin must now pass in a parameter, which can be an object, string, or function.
Remove the code
The new deprecations include a deprecation code, so they are easier to reference.
Obsolete grammar
Require. include is deprecated, warning when used. The behavior of the alarm can be Rule. The parser. RequireInclude set to allow, or banned.
Automatic Node.js polyfill has been removed
In the early days, WebPack focused on making node.jsd modules run in the browser, but things have changed, and many modules are written solely for front-end use. Webpack versions 4 or less encapsulate polyfills for many Node.js modules, and polifills will take effect once a module uses the core node.js module (such as crypto). This compatibility makes it convenient to use modules written for Node.js, but it also leads to polyfills code in packaging files, and polifills are often unnecessary. Webpack 5 stops being automatically compatible with these Node core modules and focuses on front-end compatibility. Our goal is to examine web platform compatibility, and many times the Core Node.js module is not necessary. The migration:
- Use browser-compatible modules whenever possible
- If possible, manually add polyfills for node.js modules, and an error message will appear to instruct you to do so
- Author: Please
package.json
The use ofborwser
Domain to ensure that packages can run in a browser environment. Provide additional implementations or dependencies for the browser environment to resolve compatibility issues.
Long-term cache of major changes
Deterministic chunk, module ID, and export name
New algorithms are introduced in long-term caching, which is automatically introduced in production mode. That is, a configuration like this:
chunkIds: "deterministic" moduleIds: "deterministic" mangleExports: "deterministic"
Copy the code
The algorithm assigns 3 – to 5-digit ids to modules and chunks in a deterministic manner, and 2-digit characters to output names. This is a compromise between packaging volume and long-term caching. ModuleIds/chunkIds/mangleExports: false will prohibit the default behavior, you can use the conventional algorithm by introducing a plug-in to. Note that in Webpack 4, setting moduleId/chunkIds:false to introduce a plug-in will work, but in Wepack 5 a plug-in must be provided. Migration: best in chunkIds moduleIds mangleExports use default Settings. You can also use the previous defaults in configuration chunkIds: “size”, moduleIds: “size”, mangleExports: “size”. This makes the packaging smaller, but it invalidates the cache more frequently during the packaging process. Note: The hashed module ID in WebPack 4 slowed down gZIP performance. This was related to a change in module order and has been fixed. Note: Deterministicid (Persistent ID) is enabled by default in a development environment in WebPack 5
Real content hash
Webpack 5 will use the hash of the file content when configuring contenthash. Previously, only internal file structure hashes were used. In the case of just comments and variable renaming, there is a positive impact on the long-term cache. These changes are not visible after code compression.
Development support for major changes
A named Chunk id
In development mode, the new chunk ID naming algorithm will be enabled by default, which gives readable names to chunks and file names. The ID of a module depends on its path and context. The ID of a chunk depends on the contents of the chunk. So you don’t need to use debugging like import(/* webpackChunkName: “name” */ “module”), but it still makes sense if you want to control file names in production. It is quite possible to use chunkIds: “named” in a production environment, but make sure this does not expose sensitive module names. Migration: In development mode, if you don’t like arbitrary filename changes, you can pass chunkId: “natural” to use the old numeric naming form.
Module Federation
Webpack 5 adds a new feature called “module federation” that allows developers to work together with the build results of multiple WebPacks. From a runtime point of view, modules from different builds can be wired together into a large module diagram structure. From the developer’s point of view, modules can be imported from different remote builds with minimal restrictions. See this separate guide for more details
Major changes to the new Web platform features
JSON module
The JSON module now complies with the protocol, and an alarm will be generated if the output is not the default. JSON modules no longer have named exports when imported from a strict schema ECMAScript module. Migration: Use the default export. Setting optimization.usedexports causes unused attributes to be discarded, although the default export is used. Set optimization. The mangleExport attribute name is destructive optimization (translator note: attribute name can be modified, reduce the number of characters). You can introduce jSON-like files, such as Toml, YAMl, JSON5, etc., by specifying a JSON parser in rules.parser.parse
import.meta
import.meta.webpackHot
ismodule.hot
This is also valid in strict mode ESMimport.meta.webpack
Is the main version number of Webpackimport.meta.url
Is the file URL of the current file (similar to__filename
, but as the URL of the file)
Asset module
Webpack 5 has native support for modules that represent assets. These modules either put a file into an output folder or a DataURI into a javascript package file. Both provide a URL. It can be referenced in a variety of ways:
- The old way:
import url from "./image.png"
And in themodule.rules
Set in thetype: "asset"
(When the improt’s patterns match) - New way:
new URL("./image.png", import.meta.url)
The new method preloading here allows code to run unpackaged, and this syntax in the native ECMAScript module can be executed in the browser.
Native worker support
When a new URL and new Worker/new ShareWorker/navigator serviceWorker. Register when used together, the web Worker webpack will generate a separate entrance. The syntax new Worker(new URL(“./worker.js”, import.meta.url)) is also allowed to be used unpackaged. This use of native ECMAScript modules is also supported in browsers.
URIs
Webpack 5 supports protocols in controlling interface requests.
data:
Support. Either Base64 or raw encoded content is supported. Mimetype can be mapped tomodule.rules
Each loader in. Such as:import x from "data:text/javascript,export default 42"
file:
supporthttp(s):
Support. But you need to configure itnew webpack.experiments.schemesHttp(s)UriPlugin()
*** By default, the target is the Web, and the fragmentation of URIs requests for external resources (both of which are part of externals) is also supported, e.g../file.js#fragment
Asynchronous module
Webpack 5 supports so-called asynchronous modules. These modules are not executed synchronously; they are replaced by asynchronous promises. Modules imported through import are processed automatically without additional operations, and the difference is almost unrecognizable. The module introduced via require() will return a promise. The promise’s resolve will return the original exports. In Webpack, there are several ways to introduce asynchronous modules:
- Asynchronous externals (async externals)
- The WebAssembly module in the new specification
- ECMAScritp module using top-level await
Externals
An additional external file type was introduced in WebPack 5 to address more application scenarios: PROMISE: an expression that returns a promise. The external module is asynchronous, and the promise resolve value is the module’s exports.import: the native import() is applied to a particular request. External modules are asynchronous modules. Module: Not implemented yet, but intended to import x from “…” The url is loaded via the
Major changes to the new node.js ecosystem features
resolving
Exports and imports are supported in package.json. Yarn PnP is now supported natively. See package export for more details
Development experience of major changes
Construction objective optimization
Webpack 5 allows you to pass in a list of build targets and fine-tune the version of the build target. For example: target: “node14” target: [“web”, “ES2020 “] This is a method that gives webPack information about the target of the build, telling the build what it needs, for example:
- Chunk download mechanism
- Supported syntax
stats
The STATS test format improves readability and reduces configuration complexity. The default configuration has become more concise and is suitable for large project builds as well.
- Relationships between chunks are now hidden by default. Can be achieved by
stats.chunkRelations
To open it. - Stats will now differentiate
file
andauxiliaryFiles
- Stats now returns the default hidden Module and chunk ID and can pass
stats.ids
open - The list of modules is sorted by its distance from the entry file. This one can go through
stats.modulesSort
To adjust the - The chunk list is now sorted by module name. This one can go through
stats.chunkModulesSort
To adjust the - The list of nested modules in concatenated Modules is sorted by topology order. Can be achieved by
stats.nestedModulesSort
To adjust the - Chunks and Assets now display ID prompts
- Assets and Modules will be presented in a tree form, which was previously presented in a table form
- A summary of the general information is presented at the end of the build process, showing the version of the Webpack, the name of the configuration, and the number of errors and alarms
- Hash is now hidden by default and can be found in
stats.hash
To configure - Built timestamps are now not displayed by default. Can be found in
stats.builtAt
To set. The timestamp will be shown in the final build summary output - The subcompilation process is now not shown by default. Can be achieved by
stats.children
Configure.
process
ProgressPlugin is somewhat optimized and can be optimized on the CLI with — Progress or added manually as a plug-in. It used to just keep track of the number of completed modules. Now you can count entries, dependencies, etc., all of which are displayed by default. In the past it would only show the module currently in progress. This can lead to excessive error output and even performance problems with some console. This feature is now turned off by default (activeModules property control). It also reduces unnecessary console.log output. The stderr output will now have a 500ms intercept during the build process. The Profiling pattern has also been updated to show the timing of nested process messages. This will help you analyze performance issues introduced by plug-ins. A new percentBy attribute tells the ProgressPlugin how to calculate the percentage of the process.
new webpack.ProgressPlugin({ percentBy: 'entries' });
Copy the code
To make the percentages calculated by the process precise enough, the ProgressPlugin will cache the known total number of modules and reuse it in the next build. The cache is hot started on the first startup and used and updated in subsequent builds.
Autonomous distinction naming
In WebPack 4, multiple Webpacks running in the same HTML cause conflicts because they use the same global variables for chunk loading. To fix this, you need to provide a generic name in the output.jsonpFunction configuration item. Webpack 5 now automatically introduces a uniqueName from package.json and uses it as content for output.uniquename. This value will be used to make any potentially conflicting global variables unique. Migration: To achieve unique naming, you can remove output.jsonFunction from package.json.
Automatic public path
Webpack 5 will automatically configure output.publicPath as much as possible.
Typescript type
The WebPack 5 source code supports typescript and is introduced through the NPM package. Migration: Remove @types/webpack, update references with different names.
Optimization of major changes
Nested tree shaking
Webpack can now track nested properties of output content. This will raise the performance of Tree Shaking (removing unused attributes) when reexporting namespace objects.
// inner.js
export const a = 1;
export const b = 2;
// module.js
export * as inner from './inner';
// or import * as inner from './inner'; export { inner };
// user.js
import * as module from './module';
console.log(module.inner.a);
Copy the code
In the example above, variable B (without reference) will be removed from production
Internal module tree shaking
Module inputs and dependencies between inputs are not analyzed in WebPack 4. Webpack 5 has a new configuration item, optimization.innergraph, which is enabled by default in production. This configuration analyzes symbols in the module to find dependencies from input to output. Take a look at this example:
import { something } from './something';
function usingSomething() {
return something;
}
export function test() {
return usingSomething();
}
Copy the code
The inner graph algorithm will find that something is only used when test is exported. This marks a lot of unused content so it can be removed from the package. This will remove more modules when “sideEffects”: false is set. In this example./something will be removed if test is not in use. In order to get more information about didn’t use the export, optimization. UnusedExports need to be set. To remove modules that have no sideEffects, set optimization.sideeffects. The following syntax symbols will be analyzed during the packaging process:
- Function declaration
- Class declaration
- Containing the following
export default
And variable declarations- Functional expression
- Such expressions
- Sequence expression
/*#__PURE__*/
expression- The local variable
- Imported binding
- content
Feedback: If you find something missing in this process, please make an issue to us and we will consider adding it. Using eval() in a module invalidates this optimization because the code eval executes may internally refer to all variables in the domain. This optimization is also known as Deep Scope Analysis.
CommonJs tree shaking
Webpack used to have special handling of resources exported for Commonjs, or resources exported using require(). Webpack 5 adds support for the Commonjs structure, making it possible to remove unused Commonjs output and trace the name of the referenced export from the require() call. This new feature supports the following structure:
exports|this|module.exports.xxx = ...
exports|this|module.exports = require("..." ) (reexport)
exports|this|module.exports.xxx = require("..." ).xxx (reexport)
Object.defineProperty(exports|this|module.exports, "xxx", ...)
require("abc").xxx
require("abc").xxx
- Imports from the ESM
- through
require()
Reference an ESM - Mark output types (especially for ESM imports in non-strict mode)
Object.defineProperty(exports|this|module.exports, "__esModule", { value: true|!0 })
exports|this|module.exports.__esModule = true|! 0
- More structures are likely to be supported in the future
If unparsed code is detected, WebPack will give up tracking all exported information (for performance reasons)
Side effect analysis
The sideEffect tag in package.json will allow you to manually tag modules that have no side effects and will be removed from the build if they are not in use. Webpack 5 will automatically flag modules for side effects based on the results of source code static analysis.
Optimizations per run
Webpack 5 now has the ability to analyze and optimize modules (the default behavior) on each run, which is equivalent to one entry per run. This mechanism guarantees that only the entry files will actually be used everywhere. The entry files do not affect each other.
Module concatenation
Module aggregation occurs at each runtime, resulting in a different aggregation module for each runtime. Module aggregation is a first-class citizen, and arbitrary modules and dependencies can now be implemented. ExternalModules and JSON modules were originally supported in WebPack 5. More types of modules will be supported in the future.
Conventional tree shake optimization
Export * now captures more information and does not mark the default output as being used. Export * Webpack throws a warning when it finds a conflicting export. Import () allows manual tree shaking modules, specified with comments like /* webpackExports: [” ABC “, “default”] */.
Similarities between development and production environments
We try to strike a balance between the build performance of the development environment and avoiding the problems unique to the production environment by improving the similarity between the development and production models. Webpack 5 has sideEffects optimizations turned on in both development and production modes. In WebPack 4, this optimization caused problems that only occur in production due to errors in the sideEffects markup. Turning this optimization on in the development environment allows potential problems to be exposed earlier. In many cases, the development and production environments run on operating systems with different file systems. Webpack 5 adds new errors and alarms for unusual case.
Improvements in the code generation process
Webpack detects ASI and generates shorter code Object(…) without semicolon insertion. – > (0,…). Webpack merges getters for each output into a run-time function call: r.d(x, “a”, () => a); r.d(x, “b”, () => b); -> r.d(x, {a: () => a, b: () => b}); Webpack now has a new configuration item output.environment. This configuration tells WebPack which ECMAScript features can be used in the runtime code. Normally this configuration item is not specified directly, but is configured in the target. Webpack 4 used to only generate ES5 code. Webpack 5 can now generate ES5 and ES6/ES2015 code. If you only consider supporting modern browsers, using the arrow function will make the generated code much shorter. Using const declarations with TDZ temporal dead zone yields more spec compliant code.
To optimize thetarget
configuration
In WebPack 4, target is a very crude configuration item (or other target) between Web and Node. Webpack 5 now opens up more options. The target configuration now affects more generated code than ever before.
- Chunk loading method
- The chunk of the format
- Wasm loading method
- Chunk and wASM loading methods in worker
- The use of global objects
- Whether publicPath should be automatically specified
- ECMAScript features and use of prefixes in generated code
externals
The default open- Partial node.js compatibility layer behavior (
global
.__filename
.__dirname
) - Parsing modules (
browser
Domain,exports
andimports
Conditions) - Some loaders may change the above behavior
For the reasons listed above, the choice between Web and Node is rather sketchy, and we need more information. So we allow you to specify a minimal version, such as Node10.13, and infer more attributes of the target environment. Now you can also combine multiple targets with arrays, and WebPack will find the least compatible attributes for all of them. Using arrays is also useful when using targets that do not provide complete information, such as “Web” or “Node” (no version number). For example [‘web’,’ ES2020 ‘] will combine the goals of the two sections. There is a target browserslist that will use the browser list property to determine the environment’s properties. This is the default target for WebPack when there is an available Browserslist configuration available. If not, Web will be the default target. Some combinations and features are not implemented in the current release and throw errors. They are for future features such as:
["web","node"]
The output will use the generic chunk loading method, but this is not currently implemented.["web","node"]
+output.module: true
The output will be loaded using the Module Chunk method, which is not currently implemented."web"
Will usehttp(s):
To introduce external, which is considered a module, which is not currently implemented (compromise:externalsPresets: {web: false, webAsync: true}
, this will be usedimport()
To load modules)
Chunk splitting and module size
Modules now doesn’t just use numbers to identify sizes. Now there are different size types. SplitChunksPlugin now knows how to use these different sizes and applies them to minSize and maxSize. By default, only the javascript size is computed, and you can pass in multiple values to control the scope of the calculation:
module.exports = {
optimization: {
splitChunks: {
minSize: {
javascript: 30000.webassembly: 50000,}}}};Copy the code
You can still use just numbers to mark the size. In this case, WebPack will automatically use the default size type. The mini-CSs-extract-plugin uses CSS /mini-extra as size type and calls this size type to the default types.
Performance of major changes
Persistent cache
Webpack will now use file system caching. This is configurable and can be enabled with the following configuration:
module.exports = {
cache: {
// 1. Set cache type to filesystem
type: 'filesystem'.buildDependencies: {
// 2. Add your config as buildDependency to get cache invalidation on config change
config: [__filename]
// 3. If you have other things the build depends on you can add them here
// Note that webpack, loaders and all modules referenced from your config are automatically added}}};Copy the code
Important note: By default, Webpack assumes that the node_modules file path will only be changed by the Package Manager. Hash and timestamp mechanisms for node_modules have been discarded. Now only the package name and version are taken into account. Systemwide links are available as long as resolve.symlink: false is not set (try to avoid this). Do not modify node_modules directly unless you decide to turn off the optimizations via snapshot.managedPaths: []. When using YARN Pnp, Webapck assumes that the YARN cache is immutable (it usually is). You can turn this optimization off by setting snapshot.immutablePaths: []. Cache content will be placed in node_modules/. Cache /webpack (but when node_modules is used). By default (using YARN PnP) caches are stored in.yarn/.cache/webpack. Normally you do not need to remove these caches manually, provided that all plug-ins have the correct cache handling. Many internal plug-ins also use persistent caching. Examples :SourceMapDevToolPlugin(generated sourceMap),ProgressPlugin(number of cache modules). Persistent caching automatically creates multiple cache files based on their purpose to optimize the read and write process. By default, timestamps will be used for snapshots in the development environment and file hashes will be used in the production environment. File hash also supports persistent caching on CI.
The compiler is idle and closed
The compiler needs to be closed after use. The compiler now enters and leaves idle states, and now has hooks to control those states. Plugins now use these hooks to do unimportant work. (For example, persistent caches will be stored slowly on hard disk). All remaining work needs to be done as soon as the compiler shuts down. There will be a callback to tell the compiler to close. Plug-ins and their authors should assume that users of the part may forget to close the compiler. In idle mode, all work should be done eventually. There should be no running processes when the work is done. Webpack () automatically calls close when it passes the callback function; Migration: Although using the Node.js API, make sure compier.close is called when you’re done;
The output file
Webpack used to output all files on the first build and skip writes to unmodified files during an incremental build (Watch). There will be no other changes to the output file while WebPack is running. With persistent caching added, you should have a Watch-like experience even when you restart the Webpack process, but it’s a bit wishful thinking to think that nothing else will change the output directory even if WebPack isn’t running. So WebPack now checks the files that exist in the output path and compares them to the contents of the output file in memory. Only write when the content changes. This process only happens on the first build. If new content is generated in the WebPack running process, incremental compilation will write to these files. We assume that WebPack and plug-ins only generate new files when the content changes. The cache is used to ensure that no new content is generated when the input is equal. Failure to follow this advice will delay performance. Files marked immutable (including hash content) will never be written as long as a file with the same name already exists. We assume that the file hash will change along with the file content. This assumption holds true most of the time. This may not be the case during webpack or plug-in development.
One of the main changes is some long-standing problems
Code segmentation for single file objects
Previously, projects that could only be launched from a single file (such as the Node, Webworker, and Electron main program) now support loading the required dependencies during runtime initialization. When making in chunks: “all” can use opimization. SplitChunks and optimization runtimeChunk for the target file. Note that the chunk loading of these target files is asynchronous. This makes the initial evaluation process also asynchronous. This may cause problems in output.library because the exported value is now a promise.
Update the resolver
Webpack 5 now supports enhanced- Resolve. Now the following optimizations have been made:
- More dependencies are tracked, such as trivial files
- Aliasing may now have several options
- Aliasing can now be false
- Support similar
exports
andimports
Such a property - Performance improvement
The js chunk
Chunks without JS code will no longer generate JS files. Chunks are now allowed to contain only CSS.
Future features of major changes
The experiment
Not all features are stable at the beginning. In WebPack 4 we added test features and annotated them in Changelog, but it’s not intuitive whether these features are experimental in configuration. In WebPack 5, there is a new Experiments configuration item that can be used to enable experimental features. This allows you to visually see which features are turned on. Although WebPack follows semantic versioning, it will provide an exception for experimental functionality. Experimental features may contain disruptive changes in minor versions. When this happens, we will add a clear record to Changelog. This will allow us to maintain experimental features faster, while also allowing us to stay on major releases longer to get stable features. The following experimental features will be packaged in WebPack 5:
- Support for older WebAssemblies in WebPack 4 (
experiments.syncWebAssembly
) - Based on updated features, support for the new WebAssembly (
experiments.asyncWebAssembly
)- This makes a WebAssembly module an asynchronous module
- Support for top-level await proposals (
experiments.topLevelAwait
)- At the top level is the module Shiyong
await
Make this module an asynchronous module.
- At the top level is the module Shiyong
- Package output files as modules (
experiments.outputModule
)- The IIFE(Immediately Invoked Function Expression Executes Function Expression Immediately) wrapper is now removed from the package file, enhancing the strict pattern
<script type="module">
To lazily load content, minimize it in module mode.
- The IIFE(Immediately Invoked Function Expression Executes Function Expression Immediately) wrapper is now removed from the package file, enhancing the strict pattern
This also means that WebAssembly is now supported by default.
Supported by the smallest Node version
The minimum supported Node version is now migrated from 6 to 10.13.0. Migration: Upgrade node to the latest available version.
Configuration Modification
Architecture changes
entry: {}
It is now possible to pass in an empty object (entry can be added using plug-ins)target
Supports arrays, versions, and browser listscach: Object
Remove: Cannot set content cache objectcache.type
New: Two options are available:memory
andfilesystem
- for
cache.type = "filesystem"
There are new configuration items:cache.cacheDirectory
cache.name
cache.store
cche.hashAlgorighm
cache.idleTimeout
cache.idleTimeoutForInitialSotre
cache.buildDependencies
- new
snapshot.resolveBuildDependencies
- new
snapshot.resolve
- new
snapshot.module
- new
snapshot.managedPaths
- new
snapshot.immutablePaths
- new
resolve.cache
To enable or disable the resolve cache - remove
resolve.concord
resolve.alias
Can be an array or false- new
resolve.restrictions
Allow limiting potential resolve results - new
resolve.fallback
Allows aliasing of requests that cannot be resolved - new
resolve.preferRelative
Allows parsing requests from modules to be treated as relative requests - Automatic adaptation for Node.js has been removed
node.Buffer
Has been removednode.console
Has been removednode.process
Has been removednode.*
(Node.js native module) removed- Migration: Using
resolve.alias
andProviderPlugin
. You will be prompted if an error occurs (seenode-libs-browserLearn how polyfill and mock are done in V4.)
output.filename
Passing in functions is now supported- new
output.assetModuleFilename
output.jsonpScriptType
renameoutput.scriptType
devtool
Now it’s more stringent- Format:
false | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map
- Format:
optimization.chunkIds
The new"deterministic"
configurationoptimization.moduleIds
new"deterministic"
configurationoptimization.moduleIds
new"hashed"
configurationoptimization.moduleIds
remove"total-size"
- Multiple flags for modules and Chuank have been removed
- remove
optimization.hashedModuleIds
- remove
optimization.namedChunks
.NamedChunksPlugin
Also be removed - remove
optimization.namedModules
.NamedModulesPlugin
Also be removed - remove
optimization.occurrenceOrder
- Migration: Using
chunkIds
andmoduleIds
- remove
optimization.splitChunks
test
No longer matches the name of chunk- Migration: use a test function (module, {chunkGraph}) = > chunkGraph. GetModuleChunks (module). Some (the chunk = > the chunk. The name = = = “name”)
- new
optimization.splitChunks
minRemainingSize
optimization.splitChunks
filename
Now it can be a functionoptimization.splitChunks
Size can now be a mapping object containing each source type and sizeminSize
minRemainingSize
maxSize
maxAsyncSize
maxInitialSize
optimization.splitChunks
maxAsyncSize
和maxInitialSize
A newmaxSize
: Allows defining the maximum size of different initializing chunks and asynchronous chunksoptimization.splitChunks
name:true
Removed: Autonaming is now not supported- Migrate: Use the default configuration.
chunkIds: "named"
Will provide meaningful names for your build files to facilitate debugging
- Migrate: Use the default configuration.
optimization.splitChunks.cacheGroups[].idHint
Added: Provide a hint on how to select a named Chunk IDoptimization.splitChunks
automaticNamePrefix
Has been removed- Migration: Using
idHint
To replace the
- Migration: Using
optimization.splitChunks
filename
No longer limited to the initial chunkoptimization.splitChunks
usedExports
Used exports are included when comparing modulesoptimization.splitChunks.defaultSizeTypes
New: Size type when size is identified by a number- new
optimization.mangleExports
optimization.minimizer
"..."
Can be used to reference default contentoptimization.usedExports
new"global"
Configuration that allows the ability to turn off analysis at run time and do it globally (for performance reasons)optimization.noEmitOnErrors
renameoptimization.emitOnErrors
And the logic is flipped- new
optimization.realContentHash
- remove
output.devtoolLineToLine
- Migration: No compatibility scheme
output.chunkFilename
Functions are now allowed to be passed inoutput.hotUpdateChunkFilename
, is now not allowed to pass in functions, and passing in will not take effectoutput.hotUpdateMainFilename
Passing in functions is now disallowed and will not take effectoutput.importFunctionName
Strings can be specified for substitutionimport()
To be compatible with unsupported environments- new
output.charset
Setting this to false removes script tagscharset
attribute output.hotUpdateFunction
renamedoutput.hotUpdateGlobal
output.jsonpFunction
renamedoutput.chunkLoadingGlobal
output.chunkCallbackFunction
renamedoutput.chunkLoadingGlobal
- new
output.chunkLoading
- new
output.enabledChunkLoadingTypes
- new
output.chunkFormat
module.rules
The inside of theresolve
andparser
Another way will be used to merge configurations (objects will be deeply merged, and arrays will pass through.
To reference the previous value)module.rules
parser.worker
Added to allow configuring support for workersmodule.rules
removedquery
andloaders
module.rules
options
Passing in strings is no longer supported- Migration: Pass in an object and issue if it is not supported
module.rules
newmimetype
To allow mimeType matching DataURImodule.rules
newdescriptionData
, allowing matching of data in package.jsonmodule.defaultRules
You can use"..."
To reference the default configuration- new
stats.chunkRootModules
Show the root module of Chunk - new
stats.orphanModules
Displays unissued modules - new
stats.runtime
, showing runtime modules - new
stats.chunkRelations
Show the parent, child, and brother modules - new
stats.errorStack
Show the tracing of the error stack within Webpack - new
stats.preset
Choose a Preset value - new
stats.relatedAssets
Show assets related to other assets (such as sourceMap) - In order to support
ignoreWarnings
And now abandonedstats.warningsFilter
BannerPlugin.banner
Signature changes- remove
data.basename
- remove
data.query
- The migration:
filename
In the spare
- remove
SourceMapDevToolPlugin
removelineToLine
- Migration: There is no substitute
[hash]
Hash is no longer supported during full compilation- Migration: Using
[fullhash]
To replace other hash options
- Migration: Using
[modulehash]
Has been removed- The migration using
[hash]
To replace the
- The migration using
[moduleid]
abandoned- Migration: Using
[id]
To replace the
- Migration: Using
[filebase]
Has been removed- Migration: Using
[base]
To replace
- Migration: Using
- File-based templates use new placeholders (for example, SourceMapDevToolPlugin)
[name]
[base]
[path]
[ext]
externals
There are now different signal signatures when the function is passed in({ context, request }, callback)
- Migration: Changes the signature
- new
externalsPresets
- new
experiments
(See Experiments section above) - new
watchOptions.followSymlinks
watchOptions.ignored
Can now be a regular expressionwebpack.util.serialization
Now it’s being exposed
Change the default configuration
target
The default is nowbrowserslist
(When the browser list configuration is valid)module.unsafeCache
Now the default is only truenode_modules
effectiveoptimization.moduleIds
In the production environment, the default value isdeterministic
Rather thansize
optimization.chunkIds
In the production environment, the default value isdeterministic
Rather thantotal-size
optimization.nodeEnv
innone
In mode, the default value isfalse
optimization.splitChunks.minSize
The default value is in the production environment20k
optimization.splitChunks.enforceSizeThreshold
The default value is in the production environment50k
optimization.splitChunks
minRemainingSize
The default isminSize
- This makes the number of chunks to split even smaller when the remaining chunk is very small
optimization.splitChunks
maxAsyncRequests
andmaxInitialRequests
Increased to 30 by defaultoptimization.splitChunks.cacheGroups.vendors
Is renamed tooptimization.splitChunks.cacheGroups.defaultVendors
optimization.splitChunks.cacheGroups.defaultVendors.reuseExistingChunk
The default istrue
optimization.minimizer
The target is used by default in the compact statecompress.passes: 2
- When using caching,
resolve(Loader).cache
The default istrue
resolve(Loader).cacheWithContext defaults
The default isfalse
resolveLoader.extensions
remove.json
node.global
node.__filename
andnode.__dirname
The default is node-targetfalse
stats.errorStack
The default isfalse
Loader-related changes
this.getOptions
This new API will simplify loader configuration. Allows you to pass in a JSON validation to see the details
this.exec
This method has been removed and migrated in the loader context: it can now be implemented by the Loader itself
this.getResolve
In the Loader API, getResolve(options) will incorporate various configurations, as shown in module.rules resolve. Since WebPack5 differs between publishing dependencies, it is recommended to pass in dependencyType as the configuration (e.g. “ESM “,” commonJS “)
Major internal changes
The rest of the content is relevant to the plugin author:
New plug-in order
Plug-ins for WebPack 5 will take effect before the default configuration items take effect. This enables plug-ins to use their own default values, or to use the configuration values passed in. This is a disruptive change because the plug-in can no longer rely on configured values to take effect. Migration: Configuration can only be accessed in plug-in hooks. Or better yet, avoid the configuration altogether and configure it through constructors.
Runtime module
A lot of runtime code is now moved into what are called runtime modules. These special modules are responsible for adding runtime code. They will be added to any chunk and will always be added to the runtime chunk. The “runtime requirements” that control the runtime module are added to the package file. This ensures that only run-time code is added to the package file. In the future, runtime modules will be added to a chunk that needs to be loaded so that runtime code can be loaded when needed. In most cases, the core runtime logic allows inline content to be inserted in the entry module instead of calling __webpack_require__. If there are no other modules in the package file, __webpack_require__ is not needed at all. This is a good combination of module wiring (combining multiple modules into one module). Ideally, no runtime code is required at all. Migration: If you are injecting code into the runtime through the WePack plug-in, consider replacing it with a runtime module.
serialization
A new serialization mechanism has been added so that complex objects can be serialized in WebPack. Semanization is optional, so classes that need to be serialized need to be explicitly marked (their serialization has already been implemented). All modules, dependencies, and some errors have already been serialized. Migration: Serialization is recommended to apply persistent caching when using via modules or streams
Cache plug-in
Added a caching class with a plug-in interface. This ray can be used to read and write to the cache. Depending on the configuration, different plug-ins will add different capabilities to the cache. The MemoryCachePlugin plugin adds memory caching. FileCachePlugin will add persistent (file system) caches. FileCachePlugin uses a serialization mechanism to persist and store cached objects from disk
Object Frozen Adds hooks
Classes with hooks freeze their hooks objects, so custom hook migrations can no longer be added in this way: WeakMap and a static getXXXHooks(XXX) are now recommended (e.g. The getCompilationHook(compilation) method to add generic hooks. The inner class uses the same mechanism to handle generic hooks.
Tapable upgrade
The compatibility layer set up for Webpack 3 has been removed. It was also scrapped in WebPack 4. Some of the less commonly used Tapable APIS have been removed or deprecated. Migration: Use the new Tabpable API
Phased hooks
Several stages in the encapsulation process, there are different hooks to deal with these different stages, such as optimizeDependenciesBasic optimizeDependencies and optimizeDependenciesAdvanced. These hooks have been removed to enable individual hooks to use the stage option. Look for OptimizationStages for additional optional stage values. Migration: Use the remaining hooks instead, you can add the stage option.
The Main/the Chunk ModuleTemplate abandoned
The build template has been refactored. MainTemplate ChunkTemplate/ModuleTemplate has been abandoned, templated JavascriptModulesPlugin now responsible for js. Before refactoring, JS output is controlled by Main/ChunkTemplate, and other output (such as WASM,CSS) is controlled by plug-ins. It looks like JS is a first class citizen and other outputs are second class citizens. The change with refactoring is that all outputs are controlled by their respective plug-ins. One person can now intervene in the template generation process. These hooks in JavascriptModulesPlugin now, rather than the Main/ChunkTemplate (plug-in also support hooks now, I call it the additional hooks) now have a compatibility layer, so the Main Chunk/ModuleTemplate remain, But only tap calls can be delegated to the new hook location. Migration: Follow the advice in the deprecation message. Hooks that point primarily to different locations.
Entry descriptor
If an object is passed as an entry value, it may be a string, with an array wrapped around a descriptor:
module.exports = {
entry: {
catalog: {
import: './catalog.js',}}}Copy the code
The descriptor syntax will pass in additional options.
Entry output file name
By default, the import chunk’s output filename is extracted from output.filename, but you can specify an output filename for a particular entry.
module.exports = {
entry: {
about: { import: './about.js'.filename: 'pages/[name][ext]'}}};Copy the code
Entrance to rely on
By default, each chunk of entry holds all the modules it uses. With the dependOn option, you can share modules between multiple chunks of entry:
module.exports = {
entry: {
app: { import: './app.js'.dependOn: 'react-vendors' },
'react-vendors': ['react'.'react-dom'.'prop-types']}};Copy the code
The chunks of the app will not include modules contained by React-Vendors
Entrance to the library
The entry descriptor allows you to pass in different Library options for each entry
module.exports = {
entry: {
commonjs: {
import: './lib.js'.library: {
type: 'commonjs-module'}},amd: {
import: './lib.js'.library: {
type: 'amd'}}}};Copy the code
Entry run time
The entry descriptor allows you to specify runtime for each entry. When specified, a block with this name is created that contains only the run-time code for the item. When multiple entries specify the same Runtime, the chunk of each entry contains the same runtime. This means they can use the same HTML page.
module.exports = {
entry: {
app: {
import: './app.js'.runtime: 'app-runtime'}}};Copy the code
Import chunk loading
The entry descriptor allows you to specify chunkLoading for each entry. The runtime entry will use this to load chunk using the specified method.
module.exports = {
entry: {
app: {
import: './app.js'
},
worker: {
import: './worker.js'.chunkLoading: 'importScripts'}}};Copy the code
Order and ID
Webpack used to sort modules and chunks during compilation, specifically specifying an incrementally ordered ID. Now that mechanism has been scrapped. Order will not be used as a mechanism for id generation, and the id control logic will be left entirely to the plug-in. Tuning module module and chunk sort hooks have been removed. Migration: You can no longer rely on the order of modules and chunks at compile time.
Array to set
- Compiler.modules is now a Set
- Compilation.chunks is now a collection
- Chunk.files is now a collection
Here is a compatible design that will currently print the upcoming deprecation of Warngin. Migration: Please replace the array correlation method with the collection correlation method
Compilation.fileSystemInfo
This new class can be used to cache file system-related information. He can now request time stamps for files and directories. If possible, the timestamp information comes from Watcher, otherwise from the file system. In the future, request file hashes will be added, and modules will be able to check file availability by file content rather than file hash. Migration: please use the file/contextTimestamps replace compilation. FileSystemInfo. Timestamps for file directories are now supported, which makes serialization of context modules possible. Compiler.modifiedfiles has now been introduced so that references to the changed files can be obtained (compiler.removedFiles will be implemented next).
The file system
In compiler. InputFileSystem and compiler. OutputFileSystem later, there is a new compiler. IntermediateFileSystem can for all is not seen as input or output file system operation, Such as writing records, caching or parsing output. The file system now has instances of FS and no additional methods, such as join or mkdirp, are required. But if they have methods like join and dirname, use them.
Hot update module replacement
HMR runtime has now been reconstructed for runtime modules. HotUpdateChunkTemplate have been merged into the ChunkTemplate. ChunkTemplates and plug-ins now need to control HotUpdateChunk. The javascript part of the HMR runtime has been separated from the core HMR runtime. Other module types can also control the HMR in their own way. In the future, HMR for the Mini-CSS-extract-Plugin and WASM will be possible. Migration: Because this is a newly introduced feature, no migration is required. Import.meta. WebpackHot exposes the same API as module.hot. This is also true for ESM modules in strict mode (.mjs, ‘module’ in package.json, they can’t access module).
The work queue
Webpack used to control module processes by calling functions, and there is a Semaphore to control process parallelism. Compilation. Semaphore has now been removed and now controls work queues and processes through an asynchronous loss, with a separate queue for each step:
Compilation.factorizeQueue
The module factory function is called to handle a set of dependenciesCompilation.addModuleQueue
Pricing module to build queue (storage module may be recovered from cache)Compilation.buildQueue
Build modules as needed (possibly recovering modules from the cache)Compilation.rebuildQueue
If you start manually, the module will be built againCompilation.processDependenciesQueue
Handle module dependencies
These queues have hooks to watch or listen to the progress of the task. In the future, multiple compilers may work at the same time, and task coordination may be achieved by listening on these queues. Migration: Because this is a newly introduced feature, no migration is currently required
The log report
There are now some log reports within Webpack. Stats. logging and infrastructureLogging options can be used to enable logging information.
Module and Chunk diagram
Webpack used to store modules that had been resolved in dependencies, stored modules that were already contained in chunk. This is no longer the case; all information about how modules are connected to the module diagram is now stored in the ModuleGraph class. Information about how modules are connected to chunks is now stored in the ChunkGraph class. Related information (such as chunk diagrams) is also stored in related classes. This means that the following information about modules can be removed:
- Module connections -> ModuleGraph
- Module issuer -> ModuleGraph
- Module optimization bailout -> ModuleGraph(todo: Check if ChunkGraph is needed instead)
- Module usedExports -> ModuleGraph
- Module providedExports -> ModuleGraph
- Module pre order index -> ModuleGraph
- Module post order index -> ModuleGraph
- Module depth -> ModuleGraph
- Module profile -> ModuleGraph
- Module id -> ChunkGraph
- Module hash -> ChunkGraph
- Module runtime requirements -> ChunkGraph
- Module is in chunk -> ChunkGraph
- Module is runtime module in chunk -> ChunkGraph
- Chunk runtime requirement -> ChunkGraph
Wepack used to break the link between modules and graph while recovering them from the cache. No longer necessary. Modules do not store information about diagrams because it is technically possible to reuse related information across multiple diagrams. This makes caching easier. For the vast majority of changes, there is a compatibility layer that prints the deprecation of the API when used. Migration: Use the new API in ModuleGraph and ChunkGraph
Initial fragmentation
DependenciesBlockVariables have been removed, replaced by initFragments DependencyTemplates can now by adding initFragments will be at the top of the source code into modules, InitFragments allow copying. Migration: Use InitFragments instead of inserting negative indexes into the source code.
The source type of the module
Modules must now define what types of sources are supported via module.getSourceTypes (). According to this mechanism, different plug-ins call source() with different types. For example, for javascript source type, JavascriptModulesPlugin packaged source code embedded in the file. The source code type WebAssembly will cause the WebAssemblyModulesPlugin to output a WASM file. Common source code types are supported, such as the Mini-CSs-extract-plugin that will be used to support stylesheet, inserting source code into CSS files. There is no correlation between the module type and the source type. For example, the module type JSON can use javascritp, and the module type WebAssembly /experimental can use javascript and WebAssembly. Migration: Common modules need to implement these new interface methods.
Stats related plug-ins
Statspreset,default, JSON, and toString are now available in the plugin system. Convert the current Stats to a plug-in. Migration: You don’t need to replace state functions completely, you can accommodate them. Additional information can be added to stats JSON instead of writing a separate file.
New watching
Webpack’s observer has been refactored. Previously used Chokidar and native Fsevents dependencies (only on macOS). We now rely only on the native Node.jsfs. This means there are no native dependencies in WebPack. It also captures file system information while watching. Webpack now also captures mTimes and monitors the number of events. As a result, the Watch Filessystem API has been slightly tweaked. Because we’re converting arrays to collections and objects to maps.
SizeOnlySource follows emit
Webpack now replaces the source in compilation. assets with a variant of SizeOnlySource to reduce memory usage.
Send Assets multiple times
Warning Multiple Assets emit different content to the same filename will now be an error.
Export information
The storage mode of module export information has been reconstructed in the new version. ModuleGrap now has an ExportsInfo in the Module, and each output stores the corresponding information. If the module has side effects during use, Webpack stores the location exported information. For each export, the following information is stored:
- Is this export being used? Yes, no, not static value, uncertain (please refer to
optimization.usedExports
) - Are exports provided? Yes, no, not static value, uncertain (please refer to
optimization.providedExports
) - Can exports be named or renamed? Yes, no, or not sure.
- The new name, whether the exported name is renamed (see details)
optimization.mangleExports
) - Nested export information if the export is an object that contains information about itself
- To export the named object again:
import * as X from "..." ; export { X }
- Used to represent the structure in JSON modules.
- To export the named object again:
Code generation phase
The compilation process now treats code generation as a separate compilation phase. This part is no longer in the Module. The source () and the Module getRuntimeRequirements performed behind (). This makes the entire workflow clearer. It is now possible to report progress during compilation, and the code generation process can be more visually analyzed. Migration: the Module. The source (), and the Module. The getRuntimeRequirements () is rejected. Use module.codegeneration () instead.
Rely on the reference
Webpack using a single method and type in the past to rely on application (Compilation. GetDependecyReference). This type was used to contain all information about the reference, such as the reference module that was imported or exported (if it was weak) and some sort related information. Packing all the information together makes reference dependencies expensive, and they are often called (each time someone might need some of the information). In WebPack 5, this part of the code was refactored, and some of the methods were separated out.
Compilation.factorizeQueue
Call the module factory function for a series of dependenciesCompilation.addModuleQueue
Add a module to the build queue (possibly recovered from cache)Compilation.buildQueue
Build modules when necessary (possibly storing modules in a cache)Compilation.rebuildQueue
A module that will be rebuilt if triggered manuallyCompilation.processDependenciesQueue
Handle module dependencies
Each of these queues has hooks to observe and monitor the process. In the future, multiple compilers may work together, and these multi-process collaborations can be implemented through queue interception. Migration: Since this is a newly introduced feature, nothing needs to be migrated.
logging
Webpack includes multiple logg logic inside. The stats.logging and infrastructureLogging options control the opening of these logs.
The module and the chunk
Webpack used to store parsed modules in dependencies, including modules in chunks. That won’t happen now. All information about a module is connected to the module diagram. So they never have to reference modules or influence input and output. These dependencies are easier to handle, and WebPack uses them as much as possible.
Abandoned loaders
- Null-loader this will be deprecated and used
module.exports = { resolve: { alias: { xyz$: false}}};Copy the code
Or use an absolute path
module.exports = { resolve: { alias: { [path.resolve(__dirname, '....')]: false}}};Copy the code
Small changes
Compiler.name
When generating a compiler name using absolute lujiang, be sure to use it|
or!
To separate names- The use of Spaces as separators is deprecated (paths can now contain Spaces)
- Hint: in the Stats string output,
|
Replaced by a space
SystemPlugin
Now it’s off by default- Migration: Avoid using it because the specification has been removed and you can set it
Rule.parser.system:true
To enable the
- Migration: Avoid using it because the specification has been removed and you can set it
ModuleConcatenationPlugin
: The connection is no longer blocked because DependencyVariables have been removed- That means it can now be
module
.global
.process
Concatenate or any other plug-in provided.
- That means it can now be
Stats.presetToOptions
Has been removed- Migration: Using
compilation.createStatsOptions
To replace
- Migration: Using
SingleEntryPlugin
andSingleEntryDependency
Has been removed- Migration: Using
EntryPlugin
andEntryDependency
- Migration: Using
- Chunk can now have multiple entry modules
ExtendedAPIPlugin
Has been removed- Migration: No longer needed,
__webpack_hash__
and__webpack_chunkname__
Ensures that runtime code is injected where it is needed
- Migration: No longer needed,
ProgressPlugin
The tapable context is no longer usedreportProgress
- Migration: Using
ProgressPlugin.getReporter(compiler)
To replace the
- Migration: Using
ProvidePlugin
because.mjs
The file is now available againStats
jsonerrors
andwarnings
Objects that no longer contain strings but contain information will be split into multiple properties.- Migration: Retrieve information through attributes, such as
message
- Migration: Retrieve information through attributes, such as
Compilation.hooks.normalModuleLoader
abandoned- Migration: Using
NormalModule.getCompilationHooks(compilation).loader
To replace the
- Migration: Using
NormalModuleFactory
The hooks in Waterfall have been adjusted to change from waterfall to bailing, and changing and renaming hooks will return to the waterfall function- remove
compilationParams.compilationDependencies
- The plug-in will pass
compilation.file/context/missingDependencies
Add dependencies during compilation. - The compatibility layer will put
compilationDependencies.add
The agent tofileDependencies.add
- The plug-in will pass
stats.assetsByChunkName[x]
Now it’s always an array- new
__webpack_get_script_filename__
To get the name of the script file - Package. The json
sideEffects
Will beglob-to-regex
To control, rather thanmicromatch
- This may change the semantics of some edge cases
checkContext
fromIgnorePlugin
Remove the- The new
__webpack_exports_info__
The API allows introspection of the use of the export SourceMapDevToolPlugin
It now applies to non-chunk assets as well- Removed from schema
serve
attribute
Other minor changes
- Remove the built-in directory and replace it with a runtime module
- Remove obsolete features
- BannerPlugin now supports only one parameter, which can be an object, a string, or a function
- remove
CachePlugin
ChunkentryModule
Deprecated and used ChunkGraph insteadChunk.hasEntryModule
Were abandonedChunk.addModule
Were abandonedChunk.removeModule
abandonedChunk.getNumberOfModules
abandonedChunk.modulesIterable
abandonedChunk.compareTo
abandonedChunk.containsModule
abandonedChunk.getModules
abandonedChunk.remove
abandonedChunk.moveModule
abandonedChunk.integrate
abandonedChunk.canBeIntegrated
abandonedChunk.isEmpty
abandonedChunk.modulesSize
abandonedChunk.size
abandonedChunk.integratedSize
abandonedChunk.getChunkModuleMaps
abandonedChunk.hasMduleInGraph
abandonedChunk.updateHash
The signal changesChunk.getChildIdsByOrders
Signal changes (TODO: Consider migrating toChunkGraph
)Chunk.getChildIdsByOrdersMap
Signal changes (TODO: Consider migrating toChunkGraph
)Chunk.getChunkModuleMaps
Has been removedChunk.setModules
Has been removed- Previously deprecated chunk methods are removed
- new
ChunkGraph
ChunkGroup.setParents
Has been removedChunkGroup.containsModule
Has been removedChunkGroup.remove
No longer disconnects from groups in a blockChunkGroup.compareTo
The signal changesChunkGroup.getChildrenByOrders
The signal changesChunkGroup
Index and index have been renamed pre – or post-index- The old getter is obsolete
ChunkTemplate.hooks.modules
Signal to changeChunkTemplate.hooks.render
Signal to changeChunkTemplate.updateHashForChunk
Signal to changeCompilation.hooks.optimizeChunkOrder
Has been removedCompilation.hooks.optimizeModuleOrder
Has been removedCompilation.hooks.advancedOptimizeModuleOrder
Has been removedCompilation.hooks.optimizeDependenciesBasic
Has been removedCompilation.hooks.optimizeDependenciesAdvanced
Has been removedCompilation.hooks.optimizeModulesBasic
Has been removedCompilation.hooks.optimizeModulesAdvanced
Has been removedCompilation.hooks.optimizeChunksBasic
Has been removedCompilation.hooks.optimizeChunksAdvanced
Has been removedCompilation.hooks.optimizeChunkModulesBasic
Has been removedCompilation.hooks.optimizeChunkModulesAdvanced
Has been removedCompilation.hooks.optimizeExtractedChunksBasic
Has been removedCompilation.hooks.optimizeExtractedChunks
Has been removedCompilation.hooks.optimizeExtractedChunksAdvanced
Has been removedCompilation.hooks.afterOptimizeExtractedChunks
Has been removed- new
Compilation.hooks.stillValidModule
- new
Compilation.hooks.statsPreset
- new
Compilation.hooks.statsNormalize
- new
Compilation.hooks.statsFactory
- new
Compilation.hooks.statsPrinter
Compilation.fileDependencies
.Compilation.contextDependencies
andCompilation.missingDependencies
Now it’s lazy settingCompilation.entries
Has been removed- Migration: Using
Compilation.entryDependencies
To replace
- Migration: Using
Compilation._preparedEntrypoints
Has been removeddependencyTemplates
Now it’s aDependencyTemplates
Class, rather than a simpleMap
Compilation.fileTimestamps
andcontextTimestamps
Has been removed- Migration: Using
Compilation.fileSystemInfo
To replace the
- Migration: Using
Compilation.waitForBuildingFinished
Has been removed- Migration: Use a new queue
Compilation.addModuleDependencies
Has been removedCompilation.prefetch
Has been removedCompilation.hooks.beforeHash
Now called after the module’s hash has been created- Migration: Using
Compiliation.hooks.beforeModuleHash
To replace the
- Migration: Using
Compilation.applyModuleIds
Has been removedCompilation.applyChunkIds
Has been removed- new
Compiler.root
, it points to the compiler- It will be used to cache data in webpackMaps instead of statically scoping it
- new
Compiler.hooks.afterDone
Source.emitted
No longer through compiler Settings- Migration: Check it out
Compilation.emittedAssets
- Migration: Check it out
- new
Compiler/Compilation.compilerPath
, which is the compiler’s unique name in the compiler tree (as opposed to the root compiler’s field) Module.needRebuild
abandoned- Migration: Using
Module.needBuild
To replace the
- Migration: Using
Dependency.getReference
Signature changesDependency.getExports
Signature changesDependency.getWarnings
Signature changesDependency.getErrors
Signature changesDependency.updateHash
Signature changesDependency.module
Has been removed- now
DependencyTemplate
There is a base class MultiEntryDependency
Has been removed- new
EntryDependency
EntryModuleNotFoundError
Has been removedSingleEntryPlugin
Has been removed- new
EntryPlugin
- new
Generator.getTypes
- new
Generator.getSize
Generator.generate
Signature changes- new
HotModuleReplacementPlugin.getParserHooks
Parser
Be moved toJavascriptParser
In theParserHelpers
Be moved toJavascriptParserHelpers
MainTemplate.hooks.moduleObj
Has been removedMainTemplate.hooks.currentHash
Has been removedMainTemplate.hooks.addModule
Has been removedMainTemplate.hooks.requireEnsure
Has been removedMainTemplate.hooks.globalHashPaths
Has been removedMainTemplate.hooks.globalHash
Has been removedMainTemplate.hooks.hotBootstrap
Has been removedMainTemplate.hooks
Partial signature changeModule.hash
abandonedModule.renderedHash
abandonedModule.reasons
Has been removedModule.id
abandonedModule.index
abandonedModule.index2
abandonedModule.depth
abandonedModule.issuer
abandonedModule.profile
Has been removedModule.prefetched
Has been removedModule.built
Has been removedModule.used
Has been removed- Migration: Using
Module.getUsedExports
To replace the
- Migration: Using
Module.optimizationBailout
abandonedModule.exportsArgument
Has been removedModule.optional
abandonedModule.disconnect
Has been removedModule.unseal
Has been removedModule.setChunks
Has been removedModule.addChunk
abandonedModule.removeChunk
abandonedModule.isInChunk
abandonedModule.isEntryModule
abandonedModule.getChunks
abandonedModule.getNumberOfChunks
abandonedModule.chunksIterable
abandonedModule.hasEqualsChunks
Has been removedModule.useSourceMap
Be moved toNormalModule
Module.addReason
Has been removedModule.removeReason
Has been removedModule.rewriteChunkInReasons
Has been removedModule.isUsed
Has been removed- Migration: Using
isModuleUsed
.isExportUsed
andgetUsedName
To replace the
- Migration: Using
Module.updateHash
Signature changesModule.sortItems
Has been removedModule.unbuild
Has been removed- Migration: Using
invalidateBuild
To replace the
- Migration: Using
- new
Module.getSourceTypes
- new
Module.getRuntimeRequirements
Module.size
Signature changesModuleFilenameHelpers.createFilename
Signature changesModuleProfile
Class adds more dataModuleReason
Has been removedModuleTemplate.hooks
Signature changesModuleTemplate.render
Signature changesCompiler.dependencies
Has been removed- Migration: Using
MultiCompiler.setDependencies
To replace the
- Migration: Using
MultiModule
Has been removedMultiModuleFactory
Has been removedNormalModuleFactory.fileDependencies
.NormalModuleFactory.contextDependencies
andNormalModuleFactory.missingDependencies
Now it’s lazy settingRuntimeTemplate
Method now getsruntimeRequirements
The parameters of theserve
This property is removedStats.jsonToString
Has been removedStats.filterWarnings
Has been removedStats.getChildOptions
Has been removedStats
The helper method was removedStats.toJson
Signature changed (second parameter removed)ExternalModule.external
Has been removedHarmonyInitDependency
Has been removedDependency.getInitFragments
abandoned- Migration: Using
apply
.initFragements
To replace the
- Migration: Using
- Dependent references now pass a function to module instead of a module
HarmonyImportSpecifierDependency.redirectedId
Has been removed- Migration: Using
setId
To replace the
- Migration: Using
- Acorn was upgraded from 5 to 8
- test
- Hot test cases now work on multiple objects
async-node
.node
.web
.webworker
- Test cases will now be marked as
store: "instant"
orstore: "pack"
File system cache running - The test case will now act on the identified module ID
- Hot test cases now work on multiple objects
- New tool added to sort imports (check in CI)
- When the chunk name is equal to the chunk ID, the runtime chunk name mapping will not contain an entry
- Stats cause added
resolvedModuleId
.resolvedModuleIdentifier
andresolvedModule
Property to point to the module before optimization (such as scoped promotion) - Shown in the toString output of Stats
resolvedModule
- Loader – runner upgrade github.com/webpack/loa…
- For performance reasons,
Compilation
In thefile/context/missingDependencies
Will no longer sort- Don’t rely on order
- Webpack-sources upgrade to version V2 github.com/webpack/web…
- Webpack-command support has been removed
- Verify the schema using schema-utils@2
Compiler.assetEmitted
The second parameter can carry update information- The BannerPlugin removes extra Spaces
- remove
LimitChunkCountPlugin
In theminChunkSize
- Reorganize javascript-related files into subdirectories
webpack.JavascriptModulesPlugin
->webpack.javascript.JavascriptModulesPlugin
- New Logger. GetChildLogger
- EntryOnly in DllPlugin defaults to true
- Remove special request shortening logic and use a single relative path for readable module names
- Allow webpack://urls in SourceMap to provide a relative path to the root context of webpack
- Add apis to generate and process CLI parameters for Web package configuration
- Added when using system.js as libaryTarget
__system_context__
As the context for system.js - New bigint support for DefinePlugin
- Added bigint support for basic functions such as Math
- Deleted ability to modify a compiled hash after creating it
- Remove the multiStep HotModuleReplacementPlugin mode
- When absconded objects and numbers are used,
emitAsset
In theassetInfo
Will merge - When based on
filename
Path (such as saaets),[query]
It is now a placeholder that is available - new
Compilation.deleteAsset
To correctly delete an asset and related assets that are not shared - will
require("webpack-sources")
Exposure torequire("webpack").sources
- Use Terser 5 to compress the code
- Webpack can be capitalized with a W when used at the beginning of a sentence
Reference documentation
Webpack 5 releases official documentation