Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the function of webpack5

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to use the functions of webpack5, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to use the functions of webpack5. Let's take a look.

Function cleanup cleans up deprecated functions

All features marked in webpack 4 that are about to expire have been removed in this release. So before migrating to webpack 5, make sure that the builds you run on webpack 4 don't have any functional expiration warnings.

No longer automatically reference Polyfills for Node.js modules

No longer automatically add Polyfills for Node.js built-in modules. Node.js built-in modules are referenced in any project, and Polyfills is automatically added in webpack 4 or earlier. However, webpack 5 will not do this again, and webpack will devote more energy to the compatibility of front-end modules.

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

For those class library developers, please define the browser field in package.json so that the class library can be applied at the front end.

Chunk, module ID, and export names determined for long-term cache optimization

Added long-term caching algorithm. These algorithms are enabled by default in production mode.

ChunkIds: "deterministic" ``moduleIds: "deterministic" ``mangleExports: "deterministic"

The algorithm allocates short (3-or 5-bit) digital ID to modules and chunks in a deterministic manner, which is a tradeoff between packet size and long-term cache. Because these configurations will use a determined ID and name, this means that the generated cache is no longer invalidated more frequently.

Real content hash

When using [contenthash], Webpack 5 uses the real hash of the file contents. Previously, it "only" used the hash value of the internal structure. This has a positive impact on long-term caching when only comments are modified or variables are renamed. These changes are invisible after compression.

Better development support for named code block ID

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

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

You can use chunkIds: "named" in a production environment, but be sure not to accidentally expose sensitive information about the module name.

Migration: if you don't like to change the file name in development, you can use the old digital mode through chunkIds: "natural".

Module federation

Webpack 5 adds a new feature, Module federation, which allows multiple webpack builds to work together. From a run-time point of view, multiple built modules will behave like a huge connection module diagram. From the developer's point of view, modules can be imported from a specified remote build and used with minimal restrictions.

Support for new Web platform features

Webpack 5 has also made better updates to some of the support for the Web platform.

JSON module

For example, for the JSON module, it will be consistent with the current proposal and require default export, otherwise there will be a warning message. Even if the default export is used, unused properties will be discarded by optimization.usedExports optimization, and properties will be 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, and so on).

Resource module

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

They can be used in many 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 is chosen to allow code to be run without a packaging tool. This syntax can also be used in native ECMAScript modules in browsers.

Native Worker support

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

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

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

URIs

Webpack 5 supports protocol processing in requests.

Data: is supported. Base64 or original encoding is supported. Mimetype can be mapped to loader and module types in module.rule. Example: import x from "data:text/javascript,export default 42".

File: is supported.

Http (s): is supported, but you need to choose to join through new webpack.experiments.s schemesHttp (s) UriPlugin ().

By default, these URI result in requests for external resources (which are external resources) when the target is "web".

The fragments in the request are supported. For example:. / file.js#fragment.

Asynchronous module

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

Importing them through "import" is processed automatically, requires no extra syntax, and can hardly tell the difference.

Importing them through require () returns a Promise that parses to the export.

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

Asynchronous external resources (async externals)

WebAssembly Module in the New Specification

Use the ECMAScript module of the top-level Await.

External resources

Webpack 5 adds more external types to cover more applications:

Promise: an expression evaluated as Promise. The external module is an asynchronous module, and the parsed value is used as a module export.

Import . The native import () is used to load the specified request, the external module is an asynchronous module, and the parsed value is exported as a module. The external module is an asynchronous module.

Module: it hasn't been implemented yet, but it is planned to pass import x from "..." Load the module.

Script: load a url through the ``tag and get the output from a global variable (and its optional attributes). The external module is an asynchronous module.

New ecological characteristics of Node.js

The exports and imports fields in package.json are now supported. Yarn PnP is natively supported from now on.

See package exports for more details.

Improved development experience optimized build goals (target)

Webpack 5 allows you to pass a list of targets and supports the target version. For example, 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, and

Supported syntax, such as arrowhead function

Statistics

The readability and redundancy of statistical test formats are improved. The default value has been improved to make it less verbose and suitable for large builds.

Progress

The ProgressPlugin plug-in has also made some optimizations so that you can now count not only the progress of module compilation, but also entries and dependencies. In addition, the previous demonstration progress may have a certain impact on build performance, and this upgrade has also made some performance optimizations.

Automatically add unique naming

In webpack 4, multiple webpack runtimes may conflict on the same HTML page because they use the same global variable for code 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, the output.jsonpFunction can be deleted.

Automatically add public paths

Webpack 5 automatically determines output.publicPath when possible.

Typescript Typ

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

Migration: delete @ types/webpack. Update the reference when the name is different.

Building an optimized nested tree-shaking

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

/ / inner.jsexport const a = 1x export const b = 2X * as inner from'. / inner';// or import * as inner from'. / inner'; export {inner}; / / user.jsimport * as module from'. / module';console.log (module.inner.a)

In this example, the exported b can be deleted in production mode.

Internal module tree-shaking

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

In such a module:

Import {something} from'. / something';function usingSomething () {return something;} export function test () {return usingSomething ();}

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

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

To get unused export information, you need to use optimization.unusedExports. To remove modules that have no side effects, you need to use optimization.sideEffects. You can analyze the following tags:

Function declaration

Class declaration

Export export default by default or define the following variables:

Function expression

Class expression

Sequential expression

/ * # _ _ PURE__*/ expression

Local variable

Introduced bundles (bindings)

Talkback: if you find something missing in this analysis, please report a problem and we will consider adding it.

Using eval () discards this optimization for a module because code that passes through eval can reference any tag in scope. This optimization is also known as deep range analysis.

CommonJs Tree Shaking

Webpack did not analyze export usage for CommonJs exports and require () calls.

Webpack 5 adds support for some CommonJs constructs, allowing you to eliminate unused CommonJs exports and track referenced export names from require () 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 ()

Import from ESM

Require () an ESM module

Tagged export type (special treatment for 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 constructs

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

Consistency between development and production

By improving the similarity of the two patterns, we try to find a good balance between the construction performance of the development pattern and avoiding the problems that arise only in the production mode.

Webpack 5 enables "sideEffects" optimization by default in both modes. In webpack 4, this optimization results in some errors that occur only in production mode because of the incorrect "sideEffects" tag in package.json. Enabling this optimization during development makes it faster and easier to find these problems.

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

Improve target configuration

In webpack 4, "target" is a rough choice between "web" and "node" (among others). Webpack 5 gives you more options. The target option now affects more than ever about code generation, such as the loading method of the code block, the format of the code block, whether externals is 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 a minimum version, such as "node10.13", and infer more attributes about the target environment.

It is now also allowed to combine multiple targets with an array, and webpack will determine the minimum attributes of all targets. Using 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 data from the browserslist class library to determine the properties of the environment. This goal is also used by default when a browserslist configuration is available in the project. The "web" target is used by default when no configuration is available.

Code block split and module size

Now the size of the module is a better way to express it than a single number. There are now different types of sizes.

SplitChunksPlugin now knows how to handle these different sizes and uses them for minSize and maxSize. By default, only javascript sizes 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 the size type and automatically adds this size type to the default type.

There are other build optimizations, such as single runtime improvements, module merging, generic Tree Shaking improvements, individually generated code improvements, see the webpack 5 release for details.

Performance optimized persistent caching

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

Module.exports = {cache: {/ / 1. Set the cache type to the file system type: 'filesystem', buildDependencies: {/ / 2. Add your config as buildDependency to get cache invalid config when changing config: [_ _ filename], / / 3. If you have other things to build on, you can add them here / / Note that webpack, loaders and all modules referenced from your configuration will be automatically added},},}

Important note:

By default, webpack assumes that the node_modules directory where webpack is located is only modified by the package manager. For node_modules, hashes and timestamps are skipped. For performance reasons, use only the package name and version. There is no problem as long as you do not specify resolve.symlinks: false,Symlinks (that is, npm/yarn link) (avoid it anyway). Do not directly edit files in node_modules unless you use snapshot.managedPaths: [] to eliminate the optimization. When using Yarn PnP, webpack assumes that the yarn cache is immutable (as it usually is). You can use snapshot.immutablePaths: [] to exit this optimization.

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

Many internal plug-ins also use persistence caching. For example, SourceMapDevToolPlugin (generation of cache SourceMap) or ProgressPlugin (number of cache modules)

The persistent cache automatically creates multiple cache files based on usage to optimize read and write access to the cache.

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

Compiler idle and off

The compiler now needs to shut down after use. The compiler will now enter and leave idle states and have hooks for these states. Plug-ins may use these hooks to do unimportant work. (that is, the persistent cache slowly stores the cache to disk.) When the compiler shuts down-- all remaining work should be done as quickly as possible. A callback marks the closure is complete.

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

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

Migration: when using Node.js API, be sure to call Compiler.close after the work is done.

File generation

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

With the addition of the persistence cache, you should have a similar listening experience even when the webpack process is restarted, but this assumption is too strong to assume that nothing else changes the output directory even when webpack is not running.

So webpack now examines the existing files in the output directory and compares their contents with the output files in memory. It is written to the file only when it is changed. This is done only on the first build. Any incremental build is written to a file when a new asset is generated in a running webpack process.

We assume that webpack and plug-ins generate new assets only when the content is changed. Caching should be used to ensure that new assets are not generated when the input is the same. Not following this recommendation will degrade performance.

Files marked as immutable (including content hashes) will never be written when a file with the same name already exists. We assume that when the content of the file changes, the content hash changes. This is generally true, but this may not always be the case during webpack or plug-in development.

Major changes: a long-standing problem code segmentation of a single file target

Targets that allow only a single file to be started (such as node, WebWorker, electron main) now support runtime automatic loading of dependent code snippets needed to boot.

This allows the use of chunks: "all" and optimization.runtimeChunk for these targets.

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

Update the parser

Enhanced-resolve has been updated to v5 with the following improvements:

Track more dependencies, such as missing files.

Aliases may have a variety of options

Now you can call it false.

Support functions such as exports and imports fields.

Performance improvement

Code blocks without 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 planned experimental features

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

Although webpack follows semantic versioning, it makes exceptions to experimental functionality. Experimental features may include destructive changes in minor versions of webpack. When this happens, we will add a clear comment to the change log. This will enable us to iterate over experimental features faster, while also enabling us to stay longer for stable features on major versions.

The following lab features will be released with webpack 5.

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

According to the updated specification (experiments.asyncWebAssembly), new WebAssembly support is added.

This makes a WebAssembly module an asynchronous module.

Top-level proposal for Phase III of Await (experiments.topLevelAwait)

Using await at the top level makes the module an asynchronous module.

Generate a code package (experiments.outputModule) as a module

This removes the wrapper IIFE from the code package, executes strict mode, lazily loads through ``, and minimizes compression in module mode.

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

Minimum Node.js version

The minimum supported Node.js version has been increased from 6 to 10.13.0 (LTS).

Migration: upgrade to the latest version of Node.js.

Major internal architectural changes

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

Let's introduce some of the most important internal architecture changes.

New plug-in running order

Plug-ins in webpack 5 are now applied before configuration defaults are applied. This allows the plug-in to apply its own default values or as a configuration preset. But this is also a breakthrough because plug-ins cannot rely on the setting of configuration values when they are applied.

Migration: access the configuration only in the plug-in hook. 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 so-called "runtime modules". These special modules are responsible for adding runtime code. They can be added to any block, but they are always added to the runtime block now. Runtime requirements control which runtime modules (or core runtime widgets) are added to the code package. This ensures that only the runtime code used is added to the code package. In the future, run-time modules can also be added to demand-loaded blocks to load run-time code when needed.

In most cases, the core allows you to inline the entry module when running the code, rather than calling it with _ _ webpack_require__. If there are no other modules in the code package, you don't need to use _ _ webpack_require__ at all. This is well integrated with module merging, that is, multiple modules are merged into one module. At best, there is no need for runtime code at all.

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

Serialization

We added a serialization mechanism to allow complex objects to be serialized in webpack. It 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 they be implemented serializable to benefit from persistence caching.

Plug-ins for caching

A Cache class with plug-in interface has been added. This class can be used for write and read caches. Depending on the configuration, different plug-ins can add functionality to the cache. MemoryCachePlugin adds in-memory caching. FileCachePlugin adds persistence (file system) caching. FileCachePlugin uses the serialization mechanism to persist or recover cached items to or from disk.

Tapable plug-in upgrade

The compat layer of the webpack 3 plug-in has been removed. It has been cancelled in webpack 4. Some of the less used tapable API have been deleted or discarded.

Migration: use the new tapable API.

Main/Chunk/ModuleTemplate discarded

The packaging template has been refactored. MainTemplate/ChunkTemplate/ModuleTemplate is obsolete, and now JavascriptModulesPlugin is in charge of JS templates.

Prior to that refactoring, the JS output was processed by Main/ChunkTemplate, while the other output (that is, WASM, CSS) was processed by the plug-in. So it looks like JS is a first-class citizen, while other outputs are second-class. Refactoring changes this, and all output is handled by their plug-ins.

You can still hack into some of the templates. The hook is now in JavascriptModulesPlugin, not Main/ChunkTemplate. Yes, plug-ins can also have hooks, which I call additional hooks.) There is a compatibility layer, so the Main/Chunk/ModuleTemplate still exists, but simply delegates the tap call to the new hook location.

Migration: follow the recommendations in the deprecation message. Mainly hooks pointing to different positions.

New configuration of entry file

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

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

Alternatively, you can define the file name of the output, which was previously defined through output.filename:

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

In addition, the configuration of the entry file adds the file dependency definition, the format type of the generated class library (commonjs or amd), you can also set the runtime name, and how the code block is loaded. For more details, please refer to the complete release record.

Sorting and ID

Webpack used to sort modules and blocks of code in a specific way during the compilation phase, allocating ID incrementally. It's not like that anymore. The order will no longer be used for ID generation, but instead, ID generation will be completely controlled by the plug-in. Hooks that 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 code blocks.

From array to collection (Set)

Compilation.modules is now a collection

Compilation.chunks is now a collection

Chunk.files is now a collection

There is an adaptation layer but obsolete warnings are printed.

Migration: use collection methods instead of array methods.

File system and information change

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

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

Module hot replacement

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

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

Migration: this is a new feature and no migration is required.

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 cannot access module.

Work queue

Webpack used to do module processing in the form of function calls, and there is a semaphore option that restricts parallelism. Compilation.semaphore has been removed and can now be processed using asynchronous queues, with separate queues for each step:

Compilation.factorizeQueue: calls the module factory for a set of dependencies.

Compilation.addModuleQueue: add modules to the compilation queue (cache recovery module can be used)

Compilation.buildQueue: build the module if necessary (can store the module in the cache)

Compilation.rebuildQueue: if it needs to be triggered manually, the module will be rebuilt

Compilation.processDependenciesQueue: the dependencies of the processing module.

These queues will have some hook to listen on and intercept working processes. In the future, multiple compilers will work at the same time, and compilation can be orchestrated by intercepting these queues.

Migration: this is a new feature and no migration is required.

Module and chunk diagram

Webpack used to store parsed modules in dependencies and imported modules in chunk. But it has changed. All the information about how the modules are connected in the module diagram is now stored in the class of ModulGraph. All information about how the module connects to chunk is now stored in ChunkGraph's class. Information that depends on chunk diagrams is also stored in the relevant class.

Here are some examples where the information of the module 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 diagram. There is no need to do so now. A module does not store any information about graphics and can technically be used in multiple drawings. This makes caching easier. Most of these changes have an adaptation layer that prints a deprecation warning when used.

Migration: use the new API on ModuleGraph and ChunkGraph.

Module Source Types

Modules must now define the types of source code they support through Module.getSourceTypes (). Depending on this, different plug-ins call source () with these types. For JavascriptModulesPlugin with a source type of javascript, the source code is embedded in the bundle. The WebAssemblyModulesPlugin of the source type webassembly will emit a wasm file. At the same time, custom source types are also supported. For example, mini-css-extract-plugin embeds the source code in the css file using the source type of stylesheet.

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

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

A whole new observer.

The observer used by webpack has been refactored. It previously used chokidar and native dependency fsevents (on OSX only). Now it is based only on fs in native Node.js. This means that there are no native dependencies in webpack.

It can also capture more information about the file system when listening. Currently, it can also capture mtimes and monitor event time, as well as information about missing files. To this end, WatchFileSystem API made a few minor changes. At the same time of the modification, we also convert Arrays to Sets,Objects to Maps.

SizeOnlySource after emit

Webpack now replaces Sources in Compilation.assets with SizeOnlySource to reduce memory footprint.

ExportsInfo

The storage mode of the exported information of the module is reconstructed. ModuleGraph now provides an ExportsInfo for each Module, which is used to store 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? It is uncertain whether to use it or not. (see optimization.usedExports for details)

Is export available? It is uncertain whether it will be provided. (see optimization.providedExports for details)

Can I rename the export name? I'm not sure whether to rename it or not.

If export has been renamed, it is the new name. (see optimization.mangleExports for details)

A nested ExportsInfo, if export is an object with additional information, then it is itself an object

Used to re-export namespace objects: import * as X from "..."; export {X}

Used to represent the structure in the JSON module

Code generation phase

Compiled code generation functions as a separate compilation phase. It no longer runs hidden in Module.source () and Module.getRuntimeRequirements (). This should make the process simpler. It also runs to report the progress of that phase. And make the code generation more visible when parsing.

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

Dependency reference

Webpack once had a single method and type to represent a reference to a dependency (Compilation.getDependencyReference returns a DependencyReference) this type is used to introduce all the information about the reference, such as the referenced module, what export has been introduced, and if it is a weak reference, you need to subscribe to some relevant information. By putting all this information together, it is expensive and frequent to get a reference (one information at a time).

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

The referenced module can be read from ModuleGraphConnection

The introduction of the famous guide can be obtained through Dependency.getReferencedExports ()

There will be a weak flag on Dependency's class.

Sorting is only related to HarmonyImportDependencies, which can be obtained through the sourceOrder attribute

Presentational Dependencies

This is a new Dependencies type of NormalModules: Presentational Dependencies

These dependencies are used only during the code generation phase, but not during the module diagram build process. So they can never reference modules or affect export / import.

The cost of handling these dependencies is low, and webpack will use them as much as possible

Deprecate 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,}; this is the end of the article on "how to use the functions of webpack5". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use the functions of webpack5". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report