Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Two years apart, webpack 5 is officially released!


May 31, 2021 Article blog


Table of contents


HI, after Vue 3 and React 17, I'm here again! I mprint Chinese has completed the webpack v5 Chinese document synchronization and translation work, you can seamlessly read Oh.

Document address: https://webpack.docschina.org

Document address: https://webpack.docschina.org

Document address: https://webpack.docschina.org

The important thing to say three times, our documents belong to the official, we do not have other domain names Oh, and is in real-time synchronization with the official.

On October 10, 2020, webpack was upgraded to version 5.0 and a blog directory was added to the official website. W e synchronized in a timely manner, and this article is the version we summarized after reading. Don't say much to start with the body.

Since the release of webpack4 in February 2018, webpack has not had any further major updates for the time being, and the old architecture has not changed much and left a lot of baggage in order to maintain API consistency. More than two years later, webpack 5 was officially released on October 10, 2020, bringing with it significant changes that will greatly improve the efficiency and quality of front-end engineers.

The overall direction of this major release is as follows:

  • Try using persistent caching to improve build performance.

  • Try to improve the long-term cache with better algorithms and defaults.

  • Try improving package size with better Tree Shaking and code generation.

  • Try to improve compatibility with the network platform.

  • Try not to introduce any destructive changes,

    • Clean up internal structures that are in a strange state when v4 functionality is implemented.

  • Trying to prepare for future features by introducing breakthrough changes now,

    • Stay on v5 for as long as possible.

Release Note of webpack 5 is very long, and this article attempts to extract the most concise information.

The function is cleared

Clean up deprecated features

All features marked in webpack 4 that are about to expire have been removed in this release. So before you migrate to webpack 5 make sure that the build you run on webpack 4 does not have any feature expiration warnings.

Polyfills are no longer automatically referenced for node .js modules

Polyfills are no longer automatically added to Node.js built-in modules. A ny project has a built-in module that Node.js and Polyfills are automatically added in webpack 4 or earlier. But webpack 5 will not do this again, and webpack will put more effort into front-end module compatibility.

If you have modules in your code that reference these Node.js to upgrade to webpack 5 you'll try to use the front-end modules, or manually add the right Polyfills yourself.

For developers of those class libraries, define the browser field in package.json so that the class library works on the front end.

Optimised for long-term caching

Determined Chunk, module ID, and export name

A long-term cache algorithm has been added. These algorithms are enabled by default in production mode.

chunkIds: "deterministic"``moduleIds: "deterministic"``mangleExports: "deterministic"

The algorithm determines the way to assign short (3 or 5 bit) numeric IDs to modules and chunks, a trade-off between package size and long-term caching. Because these configurations will use a determined ID and name, this means that the resulting cache no longer fails more frequently.

The real content hash

Webpack 5 uses the true file content hash value when using [contenthash] P reviously it "only" used the hash value of the internal structure. T his can have a positive effect on long-term caching when only comments are modified or variables are renamed. These changes are not visible after compression.

Better development support

Name the code block ID

In development mode, the new named code block ID algorithm, which is enabled by default, provides a human-readable name for the module (and file name). T he module ID is determined by its path, relative to context The code block ID is determined by the contents of the block.

So you no longer need to use import(/* webpackChunkName: "name" */ "module") to debug. But if you want to control the file names of your production environment, it makes sense.

You can use chunkIds: "named" in a production environment, but make sure you don't accidentally expose sensitive information about the module name.

Migration: If you don't like changing file names in development, you can use the old digital mode with chunkIds: "natural"

Module Federation

Webpack 5 adds a new feature, "Module Federation," that allows multiple webpacks to build together. F rom a runtime perspective, multiple built modules will behave like a huge connection block diagram. From the developer's point of view, modules can be imported from a specified remote build and used with minimal limitations.

Supports new Web platform features

Webpack 5 has also done a better job of improving some of the support for web platforms.

JSON module

For example, the JSON module will be consistent with the current proposal and require a default export, otherwise there will be a warning message. Even with the default export, unused properties are discarded by optimization.usedExports optimization and are disrupted by optimization.mangleExports optimization.

If you want to use a custom JSON parser, you can specify a custom JSON parser in Rule.parser.parse to import JSON-like files (for example, for toml, yaml, json5, etc.).

The resource module

Webpack 5 now provides built-in support for modules that represent resources. T hese modules can send a file to the output folder or inject a DataURI into the javascript package. Either way, they give a URL to work with.

They can be used in a number of ways:

  • import url from "./image.png" and set type: "asset" in module.rule when matching such an import. (Old method)
  • new URL("./image.png", import.meta.url) (new way)

The New Way syntax was chosen to allow code to run without packaging tools. This syntax can also be used in native ECMAScript modules in the browser.

Native Worker support

When you combine the new URL of a resource with the new Worker SharedWorker/navigator.serviceWorker.register, webpack automatically creates a new entry point for the web worker. new SharedWorker navigator.serviceWorker.register

new Worker(new URL("./worker.js", import.meta.url))

This syntax was also chosen to allow code to run without packaging tools. This syntax can also be used in the browser's native ECMAScript module.

URIs

Webpack 5 supports processing protocols in requests.

  • Support data: . B ase64 or original encoding is supported. M imetype can be mapped to loader and module types in module.rule For example: import x from "data:text/javascript,export default 42"

  • Support file: .

  • http(s): , but you need to opt in via new webpack.experiments.s schemesHttp(s)UriPlugin()

    • By default, when the target is "web," these URIs result in requests for external resources, which are external resources.

Support fragments in requests. For example: ./file.js#fragment

Asynchronous module

Webpack 5 supports so-called "asynchronous modules." These modules are not synchronously parsed, but are based on asynchronous and Promise.

Importing them through "import" is automatically processed, requires no additional syntax, and makes little difference.

Importing them through require() returns a resolution to the exported Promise.

In webpack, there are several ways to have asynchronous modules.

  • Asynchronous external resources (async externals)
  • WebAssembly module in the new specification
  • Use the ECMAScript module at the top-level Await.

External resources

Webpack 5 adds more external types to cover more apps:

promise An expression evaluated as a Promise. An external module is an asynchronous module that parses values as a module export.

import 。 T he native import() is used to load the specified request, and the external module is an asynchronous module that resolves the value as a module export. An external module is an asynchronous module.

module Not yet implemented, but plans to load the module through import x from "..."

script Loads a url with the '' label and gets the output from a global variable (and its optional properties). An external module is an asynchronous module.

The new Node .js ecological features

Exports and exports fields in package.json are now imports Yarn PnP is now natively supported.

See package exports for more details.

An improvement in the development experience

Optimized build goals

Webpack 5 allows a list of targets to be passed and supports the version of the target. For target: "node14"``target: ["web", "es2020"]

This is an easy way to provide webpack with all the information it needs to determine:

  • Code block loading mechanism, as well
  • Supported syntax, such as arrow functions

statistics

Improved readability and redundancy of statistical test formats. The default values have been improved to make them less lengthy and suitable for large builds.

Progress

ProgressPlugin plug-in has also made some optimizations, and now you can count not only the progress of module compilation, but also 入口 and 依赖 Also, previous presentations may have an impact on build performance, and this upgrade has resulted in some performance optimizations.

Add unique names automatically

In webpack 4, multiple webpack runs may conflict on the same HTML page because they use the same global variable for block loading. To solve this problem, you need to provide a custom name for the output.jsonpFunction configuration.

Webpack 5 does automatically infer a unique build name from package.json name and use it as the default value for output.uniqueName

This value is used to make all potentially conflicting global variables unique.

Migration: Because there is a unique name in package.json output.jsonpFunction can be deleted.

Public paths are added automatically

Webpack 5 automatically determines output.publicPath when possible.

Typescript type

Webpack 5 generates typescript types from the source code and exposes them through the npm package.

Migration: Delete @types/webpack The reference is updated when the name is different.

Build optimization

Nested tree-shaking

Webpack now tracks access to exported nested properties. This improves Tree Shaking when re-exporting namespace objects (clearing unused exports and confusing exports).

// inner.js
export const a = 1;
export const b = 2;


// module.js
export * as inner from './inner';
// 或 import * as inner from './inner'; export { inner };


// user.js
import * as module from './module';
console.log(module.inner.a);

In this example, you can remove the exported b in production mode.

Internal module tree-shaking

Webpack 4 does not have a dependency between the export and reference of the analysis module. Webpack 5 has a new optimization.innerGraph which is enabled by default in production mode, that analyzes the flags in the module to find dependencies between exports and references.

In such modules:

import { something } from './something';


function usingSomething() {
  return something;
}


export function test() {
  return usingSomething();
}

The internal dependency graph algorithm finds that something used only when using test export. This allows more exits to be marked as unused and more code to be omitted from the code pack.

When you set "sideEffects": false you can omit more modules. In this example, when the test export is not in use, ./something omitted.

To get unused export information, you need to use optimization.unusedExports T o remove a module without side effects, you need to use optimization.sideEffects You can analyze the following tags:

  • The function declaration

  • Class declaration

  • 默认导出export default by default or define the following variables:

    • The function expression
    • Class expression
    • Sequential expressions
    • /*#__PURE__*/
    • The local variable
    • Introduced bundles

Feedback: If you find something missing from this analysis, report a problem and we'll consider adding it.

Using eval() discards this optimization for a module because eval-passed code can reference any tag in the range. This optimization is also known as depth range analysis.

CommonJs Tree Shaking

Webpack has never used analysis for exports when CommonJs exports and require() calls.

Webpack 5 adds support for some CommonJs constructs, allowing unused CommonJs exports to be eliminated require() referenced export names to be tracked from calls.

The following constructs are supported:

  • 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()

  • Imported from ESM

  • require() an ESM module

  • Marked export type (special handling of non-strict ESM imports):

    • Object.defineProperty(exports|this|module.exports, "__esModule", { value: true|!0 })
    • exports|this|module.exports.__esModule = true|!0

  • Future plans support more construction

When unanalysed code is detected, webpack discards and does not track the export information of these modules at all (for performance reasons).

Development and production consistency issues

By improving the similarity between the two models, we try to find a good balance between building performance of the development model and avoiding problems that arise only from the production model.

Webpack 5 enables "sideEffects" optimization by default in both modes. I n webpack 4, this optimization resulted in some errors that only occur in production mode because the "sideEffects" tag in package.json is incorrect. Enabling this optimization during development makes it faster and easier to discover these issues.

In many cases, development and production take place on different operating systems, and the case sensitivity of the file system varies, so webpack 5 adds some strange case warnings/errors.

Improve target configuration

In webpack 4, "target" is a rough choice between "web" and "node" (and some others). W ebpack 5 gives you more options. target option now affects more things than ever before about generating code, such as how blocks are loaded, the format of blocks of code, whether externals are enabled by default, and so on.

In addition, for some of these cases, the choice between "web" and "node" is too rough, and we need more information. Therefore, we allow you to specify the lowest version, such as "node10.13" and infer more properties about the target environment.

Now that you are allowed to combine multiple targets with an array, webpack determines the minimum properties of all targets. U sing arrays is also useful when using targets like "web" or "node" that do not provide complete information (no version number). For example, ["web", "es2020"] combines these two partial goals.

There is a target "browserslist" that uses the data from the browserslist class library to determine the properties of the environment. T his target is also used by default when a browserslist configuration is available in the project. When no configuration is available, the "web" target is used by default.

The block of code is split with the module size

The size of the module is now a better representation than a single number. There are now different types of sizes.

SplitChunksPlugin now knows how to handle these different sizes and use them for minSize and maxSize By default, only javascript are processed, but you can now pass multiple values to manage them:

module.exports = {
  optimization: {
    splitChunks: {
      minSize: {
        javascript: 30000,
        webassembly: 50000,
      },
    },
  },
};

You can still use a number to represent the size. In this case, webpack automatically uses the default size type.

mini-css-extract-plugin uses css/mini-extra as a size type and automatically adds this size type to the default type.

There are other build optimizations, such as individual runtime improvements, module consolidation, generic Tree Shaking improvements, improvements to individual generated code, and webpack 5 announcements for details.

Performance optimization

Persistent cache

There is now a file system cache. It is optional and can be enabled with the following configurations:

module.exports = {
  cache: {
    // 1. 将缓存类型设置为文件系统
    type: 'filesystem',


    buildDependencies: {
      // 2. 将你的 config 添加为 buildDependency,以便在改变 config 时获得缓存无效
      config: [__filename],


      // 3. 如果你有其他的东西被构建依赖,你可以在这里添加它们
      // 注意,webpack、加载器和所有从你的配置中引用的模块都会被自动添加
    },
  },
};

Important note:

By default, webpack assumes that node_modules directory in which the webpack is located is modified only by the package manager. F or node_modules hash values and timestamps are skipped. F or performance reasons, only package names and versions are used. A s long as resolve.symlinks: false not specified, Symlinks (i.e. npm/yarn link is fine (avoid it anyway). D o not edit files directly node_modules unless you use snapshot.managedPaths: [] to eliminate the optimization. W hen using Yarn PnP, webpack assumes that the yarn cache is immutable (usually). You can opt out of this optimization by snapshot.immutablePaths: []

The cache is stored by default node_modules/.cache/webpack (when using node_modules) or .yarn/.cache/webpack (when Yarn PnP is used). When all plug-ins handle the cache correctly, you may never need to manually delete it.

Many internal plug-ins also use persistent caches. For SourceMapDevToolPlugin (generation of cached SourceMap) or ProgressPlugin (number of cache modules)

Persistent caches automatically create multiple cache files based on usage to optimize read and write access to the cache.

By default, timestamps are used for snapshots of development patterns, while file hashes are used for production mode. File hashing also allows persistent caching to be used in CI.

The compiler is idle and closed

The compiler now needs to be shut down after use. T he compiler now enters and leaves idle states, and has hooks for those states. P lug-ins may use these hooks to do unimportant work. ( The persistent cache is about to slowly store the cache on disk).) W hen the compiler is down -- all remaining work should be done as quickly as possible. A callback marks the completion of the shutdown.

Plug-ins and their respective authors should expect that some users may forget to turn off the compiler. T herefore, all work should eventually be done in an idle state. When work is in progress, you should prevent the process from exiting.

webpack() usage automatically calls close when a callback is passed.

Migration: When using node .js API, be sure to call Compiler.close when you're done.

File generation

Webpack used to emit all the output files on the first build, but skipped writing unaltered files during incremental (observation) builds. Suppose that nothing else changes the output file while the webpack is running.

With the addition of persistent caching, there should be a listening-like experience even when restarting the webpack process, but the assumption that nothing else changes the output directory even when the webpack is not running is too strong.

So webpack now checks the existing files in the output directory and compares its contents to the output files in memory. A file is written to a file only if it is changed. T his is only done on the first build. Any incremental build is written to the file when a new asset is generated in the running webpack process.

Let's assume that webpacks and plug-ins generate new assets only when content is changed. Y ou should use caching to ensure that no new assets are generated when you enter the same. Not following this recommendation can degrade performance.

Files marked as [不可变] including content hashings, will never be written when a file with the same name already exists. L et's assume that when the contents of a file change, the content hash changes. This is generally true, but may not always be the case during webpack or plug-in development.

Significant changes: Long-standing unresolved issues

Code segmentation for a single file target

Targets that allow only a single file to start ,such as node, WebWorker, electron main) now support the runtime to automatically load the dependent code snippets required for booting.

This chunks: "all" and optimization.runtimeChunk to be used for these targets.

Note that if the target's block of code is loaded asynchronously, this makes the initial evaluation also asynchronous. This can be a problem when using output.library because the value now exported is a Promise.

The parser has been updated

enhanced-resolve updated to v5 with the following improvements:

  • Track more dependencies, such as lost files.
  • Aliases may have several options
  • Now you can alias false
  • Features such as exports and imports fields are supported.
  • Improved performance

There is no block of code for JS

Blocks that do not contain JS code will no longer generate JS files. This allows for blocks of code that contain only CSS.

Major changes: Future plans

Experimental characteristics

In webpack 5, there is a new experiment configuration option that experiments experimental functionality to be enabled. This makes it clear which features are enabled/used.

Although webpack follows semantic versioning, it makes exceptions to experimental features. E xperimental features can include destructive changes in the secondary version of webpack. W hen this happens, we add a clear comment to the change log. This will allow us to iterate on experimental features faster, while also allowing us to stay stable for longer periods of time on major releases.

The following lab features will be published with webpack 5.

  • Old WebAssembly support, just like webpack 4 experiments.syncWebAssembly )

  • New WebAssembly support is added based on the updated specification experiments.asyncWebAssembly

    • This makes a WebAssembly module an asynchronous module.

  • Top-level Await Phase III proposal experiments.topLevelAwait )

    • Use await at the top to make the module an asynchronous module.

  • Build code experiments.outputModule as modules )

    • This removes the wrapper IIFE from the code pack, performs strict mode, loads lazy through '' and minimizes compression in module mode.

Note that this also means that WebAssembly support is now disabled by default.

Minimum Node .js version

The minimum supported Version of Node .js increased from 6 to 10.13.0 (LTS).

Migration: Upgrade to the latest node .js version.

Major internal schema changes

This part is mainly for those who want to contribute to the webpack kernel, as well as loaders, plug-in developers need to pay close attention to. I f you're just using webpack, you can ignore this part. There's a lot of content, and it's hard to understand.

Here are some of the most important changes to the internal architecture.

The new plug-in runs in order

Plug-ins in webpack 5 are now applied before the default values are applied. T his allows the plug-in to apply its own default values or as a configuration preset. But it's also a breakthrough change, because plug-ins can't rely on configuration value settings when they're applied.

Migration: Access the configuration only in plug-in hooks. Or it's best to avoid accessing the configuration altogether and get options through the constructor.

Runtime module

Most of the runtime code is moved to the so-called runtime module. T hese special modules are responsible for adding runtime code. T hey can be added to any block, but are always added to the runtime block for now. R untime Requirements controls which runtime modules (or core runtime parts) are added to the code pack. T his ensures that only the runtime code used is added to the code package. In the future, runtime modules can also be added to blocks loaded on demand to load runtime code when needed.

In most cases, the core allows the inline portal module to be inline when it runs the code, rather than calling it with __webpack_require__ I f there are no other modules in the code pack, you do not need to use __webpack_require__ at all. T his is well combined with module consolidation, where multiple modules are merged into one module. At best, runtime code is not required at all.

Migration: If you inject runtime code into the plug-in to the webpack runtime, consider using RuntimeModules instead.

serialization

We've added a serialization mechanism to allow the serialization of complex objects in webpack. I t has an optional semantics, so classes that should be serialized need to be explicitly marked (and serialized). Most modules, all dependencies, and some errors have already done so.

Migration: When using custom modules or dependencies, it is recommended that you implement them as serializable to benefit from persistent caching.

The plug-in used for caching

Added a Cache class with plug-in interface. T his class can be used to write and read caches. D epending on the configuration, different plug-ins can add functionality to the cache. MemoryCachePlugin memory caching. FileCachePlugin adds a persistent (file system) cache. FileCachePlugin uses serialization mechanisms to persist cached items to or recover from disk.

Tapable plug-in upgrade

The compat layer of the webpack 3 plug-in has been removed. I t has been cancelled in webpack 4. Some of the less-used tapable APIs are removed or discarded.

Migration: Use the new tapable API.

Main/Chunk/ModuleTemplate is abandoned

The packaging template has been refactored. MainTemplate/ChunkTemplate/ModuleTemplate was abandoned and Now Javascript Modeles Plugin is in charge of the JS template.

Prior to that refactoring, the JS output was handled by Main/ChunkTemplate, while the other output (i.e. WASM, CSS) was handled by the plug-in. T his makes it look like JS is a first-class citizen, while the other output is second-class. Refactoring changes this, and all output is handled by their plug-ins.

You can still break into some templates. H ooks are now in Javascript Modeles Plugin, not Main/ChunkTemplate. ( Yes, plug-ins can also have hooks, which I call additional hooks.) There is a compatibility layer, so Main/Chunk/ModuleTemplate still exists, but simply delegates the tap call to the new hook location.

Migration: Follow the recommendations in the deprecation message. It is mainly a hook that points to different locations.

The new configuration of the entry file

In webpack 5, the entry file can also be configured with descriptors in addition to strings and arrays of strings, such as:

module.exports = {
  entry: {
    catalog: {
      import: './catalog.js',
    },
  },
};

In addition, you can define the file names of the outputs, which were previously defined through output.filename

module.exports = {
  entry: {
    about: { import: './about.js', filename: 'pages/[name][ext]' },
  },
};

In addition, the configuration of the entry file, the addition of a file dependency definition, the format type (commonjs or amd) that generates the class library, the name of the runtime, and how the block of code is loaded, can be found in more detail in the full publishing record.

Sort with ID

Webpack used to sort modules and blocks of code in a specific way during the compilation phase, allocating IDs incrementally. T hat's not the case anymore. T he order will no longer be used for ID generation, but will instead be fully controlled in the plug-in. Hooks to optimize the order of modules and blocks of code have been removed.

Migration: During the compilation phase, you can no longer rely on the order of modules and blocks of code.

From Array to Collection (Set)

  • The Collection.modules are now a collection
  • The Collection.chunks is now a collection
  • Chunk.files is now a collection

There is a suitable layer but an abandoned warning is printed.

Migration: Use the collection method instead of the array method.

File system and information changes

In webpack 5, one is to use Compilation.fileSystemInfo instead of file/contextTimestamps to get timestamp information for files, and the other is to add Compiler.modifiedFiles to make it easier to reference the changed file.

In addition, a new API similar to compiler.inputFileSystem and compiler.outputFileSystem has been added for all fs compiler.intermediateFileSystem that are not considered input or output, such as writing records, caching, or output profiling.

Module hot replacement

The HMR runtime has been refactored as a runtime module. HotUpdateChunkTemplate has been merged into ChunkTemplate ChunkTemplates and plugins should also handle HotUpdateChunk

The javascript portion of the HMR runtime has been separated from the core HMR run clock. O ther module types can now handle HMR in their own way. In the future, this will enable HMR to handle modules such as mini-css-extract-plugin or WASM.

Migration: This is a new feature and does not require migration.

import.meta.webpackHot exposes the same API as module.hot Of course, it can be used in ESM modules (.mjs, type: "module" in package.json), which do not have access to module

The work queue

Webpack used to be modular in the form of function calls, and there was a semaphore option that limited parallelity. Compilation.semaphore has been removed and can now be processed using asynchronous queues, each with a separate queue:

  • Compilation.factorizeQueue Call the module factory for a set of dependencies.
  • Compilation.addModuleQueue Add modules to the compilation queue (you can use cache recovery modules)
  • Compilation.buildQueue Build modules if necessary (you can store modules in a cache)
  • Compilation.rebuildQueue If you need to trigger manually, the module is rebuilt
  • Compilation.processDependenciesQueue Handles the module's dependencies.

These queues have hooks to listen for and block the process of work. In the future, multiple compilers will work at the same time, orchestrating compilations by blocking these queues.

Migration: This is a new feature and does not require migration.

Modules and chunk diagrams

Webpack once stored parsed modules in dependencies and introduced modules in chunk. B ut that has changed. A ll the information about how modules connect in the module diagram is now stored in the class of ModulGraph. A ll information about how the module connects to chunk is now stored in ChunkGraph's class. Information that depends on the chunk diagram is also stored in the relevant class.

Here are some examples of modules where information has been moved:

  • Module connections -> ModuleGraph
  • Module issuer -> ModuleGraph
  • Module optimization bailout -> ModuleGraph (TODO: check if it should ChunkGraph instead)

When the module is recovered from the cache, webpack disconnects the module from the figure. T here is no need to do so now. A module does not store any information about graphics and can technically be used in multiple graphics. T his makes the cache easier. Most of these changes have an adapter layer that prints an deprecation warning when used.

Migration: Use the new APIs on ModuleGraph and ChunkGraph.

Module Source Types

Modules must now define the types of source code they support through Module.getSourceTypes() B ased on this, different plug-ins call source() with these types. F or javascript JavascriptModulesPlugin the source code is embedded in the bundle. WebAssemblyModulesPlugin of the source type webassembly emits a wasm file. Custom source types are also supported, for example, mini-css-extract-plugin embeds the source code into the css file using the source type stylesheet

There is no relationship between the module type and the source type. Even if the module type is json you can use javascript and webassembly/experimental with the source type javascript and the module type webassembly

Migration: Custom modules need to implement these new interface methods.

A brand new observer

The observer used by webpack has been refactored. I t previously used chokidar and native dependent fsevents (on OSX only). I t is now based only on fs in the native Node .js. This means that there is no native dependency in webpack.

It also captures more information about the file system while listening. C urrently, it can also capture mtimes and monitor event times, as well as information about lost files. T o do this, WatchFileSystem API made a small change. At the same time as the modifications, we convert Arrays to Sets and Objects to Maps.

SizeOnlySource after emit

Webpack now Compilation.assets with SizeOnlySource to reduce memory footprint.

ExportsInfo

The storage of module export information is refactored. M oduleGraph now provides an ExportsInfo for each Module that stores information for each export. If the module is used only as a side effect, it also stores information about the unknown export.

For each export, the following information is stored:

  • Do you want to use export? W hether to use it is not certain. (See optimization.usedExports

  • Is export available? W hether it is available is uncertain. (See optimization.providedExports

  • Can I rename the export name? Whether to rename is also uncertain

  • If export has been renamed, it is the new name. (See optimization.mangleExports

  • A nested ExportsInfo, if it is an object with additional information, is an object in itself

    • Used to re-export namespace objects: import * as X from "..."; export { X };
    • Used to represent the structure in the JSON module

The code generation phase

The compiled code generation function acts as a separate compilation phase. I t no longer runs in Module.source() and Module.getRuntimeRequirements() T his should make the process cleaner. I t also runs a report on the progress of the phase. And make code generation more visible during profiling.

Migration: Module.source() and Module.getRuntimeRequirements() are deprecated. Use Module.codeGeneration() instead.

Dependency reference

Webpack once had a single method and type to represent a reference to a Compilation.getDependencyReference returns a DependencyReference type used to introduce all the information about the reference, such as the referenced module, which exports have been introduced, and, if so, to subscribe to some relevant information. By building all this information together, the cost of getting a reference is high and frequent (one message at a time).

In webpack5, this part of the code base is refactored and the method is split.

  • Referenced modules can be read from ModuleGraphConnection
  • The imported export name can be obtained through Dependency.getReferencedExports()
  • There will be a weak flag on the class of Dependency
  • Sorting is only relevant HarmonyImportDependencies and can be obtained through sourceOrder property

Presentational Dependencies

This is a new type of Dependencies for NormalModules Presentation Dependencies

These dependencies are used only during the code generation phase, but not during the building of the block diagram. So they can never reference modules or affect exports/imports.

These dependencies are less expensive to process and webpack uses them whenever possible

Deprecation loaders

  • null-loader

Has been deprecated. use

  module.exports = {
    resolve: {
      alias: {
        xyz$: false,
      },
    },
  };

Or use an absolute path

  module.exports = {
    resolve: {
      alias: {
        [path.resolve(__dirname, '....')]: false,
      },
    },
  };

summary

Much of webpack 5's work revolves around optimization, removing obsolete content from 4, adding long-term caching, optimizing the kernel, and so on. This article is just a focus for you to explain, specific changes please refer to the official documents.

Official website: https://webpack.js.org Chinese documents: https://webapck.docschina.org

Above is W3Cschool编程狮 about two years away, webpack 5 officially released! Related to the introduction, I hope to help you.