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: Pleasepackage.jsonThe use ofborwserDomain 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.webpackHotismodule.hotThis is also valid in strict mode ESM
  • import.meta.webpackIs the main version number of Webpack
  • import.meta.urlIs 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.rulesSet 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.rulesEach loader in. Such as:import x from "data:text/javascript,export default 42"
  • file:support
  • http(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 bystats.chunkRelationsTo open it.
  • Stats will now differentiatefileandauxiliaryFiles
  • Stats now returns the default hidden Module and chunk ID and can passstats.idsopen
  • The list of modules is sorted by its distance from the entry file. This one can go throughstats.modulesSortTo adjust the
  • The chunk list is now sorted by module name. This one can go throughstats.chunkModulesSortTo adjust the
  • The list of nested modules in concatenated Modules is sorted by topology order. Can be achieved bystats.nestedModulesSortTo 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 instats.hashTo configure
  • Built timestamps are now not displayed by default. Can be found instats.builtAtTo set. The timestamp will be shown in the final build summary output
  • The subcompilation process is now not shown by default. Can be achieved bystats.childrenConfigure.

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 followingexport defaultAnd 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
  • throughrequire()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 thetargetconfiguration

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
  • externalsThe default open
  • Partial node.js compatibility layer behavior (global.__filename.__dirname)
  • Parsing modules (browserDomain,exportsandimportsConditions)
  • 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: trueThe 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 similarexportsandimportsSuch 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 ShiyongawaitMake this module an asynchronous module.
  • 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.

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)
  • targetSupports arrays, versions, and browser lists
  • cach: ObjectRemove: Cannot set content cache object
  • cache.typeNew: Two options are available:memoryandfilesystem
  • forcache.type = "filesystem"There are new configuration items:
    • cache.cacheDirectory
    • cache.name
    • cache.store
    • cche.hashAlgorighm
    • cache.idleTimeout
    • cache.idleTimeoutForInitialSotre
    • cache.buildDependencies
  • newsnapshot.resolveBuildDependencies
  • newsnapshot.resolve
  • newsnapshot.module
  • newsnapshot.managedPaths
  • newsnapshot.immutablePaths
  • newresolve.cacheTo enable or disable the resolve cache
  • removeresolve.concord
  • resolve.aliasCan be an array or false
  • newresolve.restrictionsAllow limiting potential resolve results
  • newresolve.fallbackAllows aliasing of requests that cannot be resolved
  • newresolve.preferRelativeAllows parsing requests from modules to be treated as relative requests
  • Automatic adaptation for Node.js has been removed
    • node.BufferHas been removed
    • node.consoleHas been removed
    • node.processHas been removed
    • node.*(Node.js native module) removed
    • Migration: Usingresolve.aliasandProviderPlugin. You will be prompted if an error occurs (seenode-libs-browserLearn how polyfill and mock are done in V4.)
  • output.filenamePassing in functions is now supported
  • newoutput.assetModuleFilename
  • output.jsonpScriptTyperenameoutput.scriptType
  • devtoolNow it’s more stringent
    • Format:false | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map
  • optimization.chunkIdsThe new"deterministic"configuration
  • optimization.moduleIdsnew"deterministic"configuration
  • optimization.moduleIdsnew"hashed"configuration
  • optimization.moduleIdsremove"total-size"
  • Multiple flags for modules and Chuank have been removed
    • removeoptimization.hashedModuleIds
    • removeoptimization.namedChunks.NamedChunksPluginAlso be removed
    • removeoptimization.namedModules.NamedModulesPlugin Also be removed
    • removeoptimization.occurrenceOrder
    • Migration: UsingchunkIdsandmoduleIds
  • optimization.splitChunks testNo longer matches the name of chunk
    • Migration: use a test function (module, {chunkGraph}) = > chunkGraph. GetModuleChunks (module). Some (the chunk = > the chunk. The name = = = “name”)
  • newoptimization.splitChunks minRemainingSize
  • optimization.splitChunks filenameNow it can be a function
  • optimization.splitChunksSize can now be a mapping object containing each source type and size
    • minSize
    • minRemainingSize
    • maxSize
    • maxAsyncSize
    • maxInitialSize
  • optimization.splitChunks maxAsyncSizemaxInitialSizeA newmaxSize: Allows defining the maximum size of different initializing chunks and asynchronous chunks
  • optimization.splitChunks name:trueRemoved: Autonaming is now not supported
    • Migrate: Use the default configuration.chunkIds: "named"Will provide meaningful names for your build files to facilitate debugging
  • optimization.splitChunks.cacheGroups[].idHintAdded: Provide a hint on how to select a named Chunk ID
  • optimization.splitChunks automaticNamePrefixHas been removed
    • Migration: UsingidHintTo replace the
  • optimization.splitChunks filenameNo longer limited to the initial chunk
  • optimization.splitChunks usedExportsUsed exports are included when comparing modules
  • optimization.splitChunks.defaultSizeTypesNew: Size type when size is identified by a number
  • newoptimization.mangleExports
  • optimization.minimizer "..."Can be used to reference default content
  • optimization.usedExportsnew"global"Configuration that allows the ability to turn off analysis at run time and do it globally (for performance reasons)
  • optimization.noEmitOnErrorsrenameoptimization.emitOnErrorsAnd the logic is flipped
  • newoptimization.realContentHash
  • removeoutput.devtoolLineToLine
    • Migration: No compatibility scheme
  • output.chunkFilenameFunctions are now allowed to be passed in
  • output.hotUpdateChunkFilename, is now not allowed to pass in functions, and passing in will not take effect
  • output.hotUpdateMainFilenamePassing in functions is now disallowed and will not take effect
  • output.importFunctionNameStrings can be specified for substitutionimport()To be compatible with unsupported environments
  • newoutput.charsetSetting this to false removes script tagscharsetattribute
  • output.hotUpdateFunctionrenamedoutput.hotUpdateGlobal
  • output.jsonpFunctionrenamedoutput.chunkLoadingGlobal
  • output.chunkCallbackFunctionrenamedoutput.chunkLoadingGlobal
  • newoutput.chunkLoading
  • newoutput.enabledChunkLoadingTypes
  • newoutput.chunkFormat
  • module.rulesThe inside of theresolveandparserAnother 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.workerAdded to allow configuring support for workers
  • module.rulesremovedqueryandloaders
  • module.rules optionsPassing in strings is no longer supported
    • Migration: Pass in an object and issue if it is not supported
  • module.rulesnewmimetypeTo allow mimeType matching DataURI
  • module.rulesnewdescriptionData, allowing matching of data in package.json
  • module.defaultRulesYou can use"..."To reference the default configuration
  • newstats.chunkRootModulesShow the root module of Chunk
  • newstats.orphanModulesDisplays unissued modules
  • newstats.runtime, showing runtime modules
  • newstats.chunkRelationsShow the parent, child, and brother modules
  • newstats.errorStackShow the tracing of the error stack within Webpack
  • newstats.presetChoose a Preset value
  • newstats.relatedAssetsShow assets related to other assets (such as sourceMap)
  • In order to supportignoreWarningsAnd now abandonedstats.warningsFilter
  • BannerPlugin.bannerSignature changes
    • removedata.basename
    • removedata.query
    • The migration:filenameIn the spare
  • SourceMapDevToolPluginremovelineToLine
    • Migration: There is no substitute
  • [hash]Hash is no longer supported during full compilation
    • Migration: Using[fullhash]To replace other hash options
  • [modulehash]Has been removed
    • The migration using[hash]To replace the
  • [moduleid]abandoned
    • Migration: Using[id]To replace the
  • [filebase]Has been removed
    • Migration: Using[base]To replace
  • File-based templates use new placeholders (for example, SourceMapDevToolPlugin)
    • [name]
    • [base]
    • [path]
    • [ext]
  • externalsThere are now different signal signatures when the function is passed in({ context, request }, callback)
    • Migration: Changes the signature
  • newexternalsPresets
  • newexperiments(See Experiments section above)
  • newwatchOptions.followSymlinks
  • watchOptions.ignoredCan now be a regular expression
  • webpack.util.serializationNow it’s being exposed

Change the default configuration

  • targetThe default is nowbrowserslist(When the browser list configuration is valid)
  • module.unsafeCacheNow the default is only truenode_moduleseffective
  • optimization.moduleIdsIn the production environment, the default value isdeterministicRather thansize
  • optimization.chunkIdsIn the production environment, the default value isdeterministicRather thantotal-size
  • optimization.nodeEnvinnoneIn mode, the default value isfalse
  • optimization.splitChunks.minSizeThe default value is in the production environment20k
  • optimization.splitChunks.enforceSizeThresholdThe default value is in the production environment50k
  • optimization.splitChunks minRemainingSizeThe default isminSize
    • This makes the number of chunks to split even smaller when the remaining chunk is very small
  • optimization.splitChunks maxAsyncRequestsandmaxInitialRequestsIncreased to 30 by default
  • optimization.splitChunks.cacheGroups.vendorsIs renamed tooptimization.splitChunks.cacheGroups.defaultVendors
  • optimization.splitChunks.cacheGroups.defaultVendors.reuseExistingChunkThe default istrue
  • optimization.minimizerThe target is used by default in the compact statecompress.passes: 2
  • When using caching,resolve(Loader).cacheThe default istrue
  • resolve(Loader).cacheWithContext defaultsThe default isfalse
  • resolveLoader.extensionsremove.json
  • node.global node.__filenameandnode.__dirnameThe default is node-targetfalse
  • stats.errorStackThe 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.factorizeQueueThe module factory function is called to handle a set of dependencies
  • Compilation.addModuleQueuePricing module to build queue (storage module may be recovered from cache)
  • Compilation.buildQueueBuild modules as needed (possibly recovering modules from the cache)
  • Compilation.rebuildQueueIf you start manually, the module will be built again
  • Compilation.processDependenciesQueueHandle 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 tooptimization.usedExports)
  • Are exports provided? Yes, no, not static value, uncertain (please refer tooptimization.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.

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.factorizeQueueCall the module factory function for a series of dependencies
  • Compilation.addModuleQueueAdd a module to the build queue (possibly recovered from cache)
  • Compilation.buildQueueBuild modules when necessary (possibly storing modules in a cache)
  • Compilation.rebuildQueueA module that will be rebuilt if triggered manually
  • Compilation.processDependenciesQueueHandle 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.nameWhen 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
  • SystemPluginNow it’s off by default
    • Migration: Avoid using it because the specification has been removed and you can set itRule.parser.system:trueTo enable the
  • ModuleConcatenationPlugin: The connection is no longer blocked because DependencyVariables have been removed
    • That means it can now bemodule.global.processConcatenate or any other plug-in provided.
  • Stats.presetToOptionsHas been removed
    • Migration: Usingcompilation.createStatsOptionsTo replace
  • SingleEntryPluginandSingleEntryDependencyHas been removed
    • Migration: UsingEntryPluginandEntryDependency
  • Chunk can now have multiple entry modules
  • ExtendedAPIPluginHas been removed
    • Migration: No longer needed,__webpack_hash__and__webpack_chunkname__Ensures that runtime code is injected where it is needed
  • ProgressPluginThe tapable context is no longer usedreportProgress
    • Migration: UsingProgressPlugin.getReporter(compiler)To replace the
  • ProvidePluginbecause.mjsThe file is now available again
  • StatsjsonerrorsandwarningsObjects that no longer contain strings but contain information will be split into multiple properties.
    • Migration: Retrieve information through attributes, such asmessage
  • Compilation.hooks.normalModuleLoaderabandoned
    • Migration: UsingNormalModule.getCompilationHooks(compilation).loaderTo replace the
  • NormalModuleFactoryThe hooks in Waterfall have been adjusted to change from waterfall to bailing, and changing and renaming hooks will return to the waterfall function
  • removecompilationParams.compilationDependencies
    • The plug-in will passcompilation.file/context/missingDependenciesAdd dependencies during compilation.
    • The compatibility layer will putcompilationDependencies.addThe agent tofileDependencies.add
  • stats.assetsByChunkName[x]Now it’s always an array
  • new__webpack_get_script_filename__To get the name of the script file
  • Package. The jsonsideEffectsWill beglob-to-regexTo control, rather thanmicromatch
    • This may change the semantics of some edge cases
  • checkContextfromIgnorePluginRemove the
  • The new__webpack_exports_info__ The API allows introspection of the use of the export
  • SourceMapDevToolPluginIt now applies to non-chunk assets as well
  • Removed from schemaserveattribute

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
  • removeCachePlugin
  • ChunkentryModuleDeprecated and used ChunkGraph instead
  • Chunk.hasEntryModuleWere abandoned
  • Chunk.addModuleWere abandoned
  • Chunk.removeModuleabandoned
  • Chunk.getNumberOfModulesabandoned
  • Chunk.modulesIterableabandoned
  • Chunk.compareToabandoned
  • Chunk.containsModuleabandoned
  • Chunk.getModulesabandoned
  • Chunk.removeabandoned
  • Chunk.moveModuleabandoned
  • Chunk.integrateabandoned
  • Chunk.canBeIntegratedabandoned
  • Chunk.isEmptyabandoned
  • Chunk.modulesSizeabandoned
  • Chunk.sizeabandoned
  • Chunk.integratedSizeabandoned
  • Chunk.getChunkModuleMapsabandoned
  • Chunk.hasMduleInGraphabandoned
  • Chunk.updateHashThe signal changes
  • Chunk.getChildIdsByOrdersSignal changes (TODO: Consider migrating toChunkGraph)
  • Chunk.getChildIdsByOrdersMapSignal changes (TODO: Consider migrating toChunkGraph)
  • Chunk.getChunkModuleMapsHas been removed
  • Chunk.setModulesHas been removed
  • Previously deprecated chunk methods are removed
  • newChunkGraph
  • ChunkGroup.setParentsHas been removed
  • ChunkGroup.containsModuleHas been removed
  • ChunkGroup.removeNo longer disconnects from groups in a block
  • ChunkGroup.compareToThe signal changes
  • ChunkGroup.getChildrenByOrdersThe signal changes
  • ChunkGroupIndex and index have been renamed pre – or post-index
    • The old getter is obsolete
  • ChunkTemplate.hooks.modulesSignal to change
  • ChunkTemplate.hooks.renderSignal to change
  • ChunkTemplate.updateHashForChunkSignal to change
  • Compilation.hooks.optimizeChunkOrderHas been removed
  • Compilation.hooks.optimizeModuleOrderHas been removed
  • Compilation.hooks.advancedOptimizeModuleOrderHas been removed
  • Compilation.hooks.optimizeDependenciesBasicHas been removed
  • Compilation.hooks.optimizeDependenciesAdvancedHas been removed
  • Compilation.hooks.optimizeModulesBasicHas been removed
  • Compilation.hooks.optimizeModulesAdvancedHas been removed
  • Compilation.hooks.optimizeChunksBasicHas been removed
  • Compilation.hooks.optimizeChunksAdvancedHas been removed
  • Compilation.hooks.optimizeChunkModulesBasicHas been removed
  • Compilation.hooks.optimizeChunkModulesAdvancedHas been removed
  • Compilation.hooks.optimizeExtractedChunksBasicHas been removed
  • Compilation.hooks.optimizeExtractedChunksHas been removed
  • Compilation.hooks.optimizeExtractedChunksAdvancedHas been removed
  • Compilation.hooks.afterOptimizeExtractedChunksHas been removed
  • newCompilation.hooks.stillValidModule
  • newCompilation.hooks.statsPreset
  • newCompilation.hooks.statsNormalize
  • newCompilation.hooks.statsFactory
  • newCompilation.hooks.statsPrinter
  • Compilation.fileDependencies.Compilation.contextDependenciesandCompilation.missingDependenciesNow it’s lazy setting
  • Compilation.entriesHas been removed
    • Migration: UsingCompilation.entryDependenciesTo replace
  • Compilation._preparedEntrypointsHas been removed
  • dependencyTemplatesNow it’s aDependencyTemplatesClass, rather than a simpleMap
  • Compilation.fileTimestampsandcontextTimestampsHas been removed
    • Migration: UsingCompilation.fileSystemInfoTo replace the
  • Compilation.waitForBuildingFinishedHas been removed
    • Migration: Use a new queue
  • Compilation.addModuleDependenciesHas been removed
  • Compilation.prefetchHas been removed
  • Compilation.hooks.beforeHashNow called after the module’s hash has been created
    • Migration: UsingCompiliation.hooks.beforeModuleHashTo replace the
  • Compilation.applyModuleIdsHas been removed
  • Compilation.applyChunkIdsHas been removed
  • newCompiler.root, it points to the compiler
    • It will be used to cache data in webpackMaps instead of statically scoping it
  • newCompiler.hooks.afterDone
  • Source.emittedNo longer through compiler Settings
    • Migration: Check it outCompilation.emittedAssets
  • newCompiler/Compilation.compilerPath, which is the compiler’s unique name in the compiler tree (as opposed to the root compiler’s field)
  • Module.needRebuildabandoned
    • Migration: UsingModule.needBuildTo replace the
  • Dependency.getReferenceSignature changes
  • Dependency.getExportsSignature changes
  • Dependency.getWarningsSignature changes
  • Dependency.getErrorsSignature changes
  • Dependency.updateHashSignature changes
  • Dependency.moduleHas been removed
  • nowDependencyTemplateThere is a base class
  • MultiEntryDependencyHas been removed
  • newEntryDependency
  • EntryModuleNotFoundErrorHas been removed
  • SingleEntryPluginHas been removed
  • newEntryPlugin
  • newGenerator.getTypes
  • newGenerator.getSize
  • Generator.generateSignature changes
  • newHotModuleReplacementPlugin.getParserHooks
  • ParserBe moved toJavascriptParserIn the
  • ParserHelpersBe moved toJavascriptParserHelpers
  • MainTemplate.hooks.moduleObjHas been removed
  • MainTemplate.hooks.currentHashHas been removed
  • MainTemplate.hooks.addModuleHas been removed
  • MainTemplate.hooks.requireEnsureHas been removed
  • MainTemplate.hooks.globalHashPathsHas been removed
  • MainTemplate.hooks.globalHashHas been removed
  • MainTemplate.hooks.hotBootstrapHas been removed
  • MainTemplate.hooksPartial signature change
  • Module.hashabandoned
  • Module.renderedHashabandoned
  • Module.reasonsHas been removed
  • Module.idabandoned
  • Module.indexabandoned
  • Module.index2abandoned
  • Module.depthabandoned
  • Module.issuerabandoned
  • Module.profileHas been removed
  • Module.prefetchedHas been removed
  • Module.builtHas been removed
  • Module.usedHas been removed
    • Migration: UsingModule.getUsedExportsTo replace the
  • Module.optimizationBailoutabandoned
  • Module.exportsArgumentHas been removed
  • Module.optionalabandoned
  • Module.disconnectHas been removed
  • Module.unsealHas been removed
  • Module.setChunksHas been removed
  • Module.addChunkabandoned
  • Module.removeChunkabandoned
  • Module.isInChunkabandoned
  • Module.isEntryModuleabandoned
  • Module.getChunksabandoned
  • Module.getNumberOfChunksabandoned
  • Module.chunksIterableabandoned
  • Module.hasEqualsChunksHas been removed
  • Module.useSourceMapBe moved toNormalModule
  • Module.addReasonHas been removed
  • Module.removeReasonHas been removed
  • Module.rewriteChunkInReasonsHas been removed
  • Module.isUsedHas been removed
    • Migration: UsingisModuleUsed.isExportUsedandgetUsedNameTo replace the
  • Module.updateHashSignature changes
  • Module.sortItemsHas been removed
  • Module.unbuildHas been removed
    • Migration: UsinginvalidateBuildTo replace the
  • newModule.getSourceTypes
  • newModule.getRuntimeRequirements
  • Module.sizeSignature changes
  • ModuleFilenameHelpers.createFilenameSignature changes
  • ModuleProfileClass adds more data
  • ModuleReasonHas been removed
  • ModuleTemplate.hooksSignature changes
  • ModuleTemplate.renderSignature changes
  • Compiler.dependenciesHas been removed
    • Migration: UsingMultiCompiler.setDependenciesTo replace the
  • MultiModuleHas been removed
  • MultiModuleFactoryHas been removed
  • NormalModuleFactory.fileDependencies.NormalModuleFactory.contextDependenciesandNormalModuleFactory.missingDependenciesNow it’s lazy setting
  • RuntimeTemplateMethod now getsruntimeRequirementsThe parameters of the
  • serveThis property is removed
  • Stats.jsonToStringHas been removed
  • Stats.filterWarningsHas been removed
  • Stats.getChildOptionsHas been removed
  • StatsThe helper method was removed
  • Stats.toJsonSignature changed (second parameter removed)
  • ExternalModule.externalHas been removed
  • HarmonyInitDependencyHas been removed
  • Dependency.getInitFragmentsabandoned
    • Migration: Usingapply.initFragementsTo replace the
  • Dependent references now pass a function to module instead of a module
  • HarmonyImportSpecifierDependency.redirectedIdHas been removed
    • Migration: UsingsetIdTo replace the
  • Acorn was upgraded from 5 to 8
  • test
    • Hot test cases now work on multiple objectsasync-node.node.web.webworker
    • Test cases will now be marked asstore: "instant"orstore: "pack"File system cache running
    • The test case will now act on the identified module ID
  • 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 addedresolvedModuleId.resolvedModuleIdentifierandresolvedModuleProperty to point to the module before optimization (such as scoped promotion)
  • Shown in the toString output of StatsresolvedModule
  • Loader – runner upgrade github.com/webpack/loa…
  • For performance reasons,CompilationIn thefile/context/missingDependenciesWill 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.assetEmittedThe second parameter can carry update information
  • The BannerPlugin removes extra Spaces
  • removeLimitChunkCountPluginIn 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,emitAssetIn theassetInfoWill merge
  • When based onfilenamePath (such as saaets),[query]It is now a placeholder that is available
  • newCompilation.deleteAssetTo correctly delete an asset and related assets that are not shared
  • willrequire("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