In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to configure Webpack", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to configure Webpack.
Why webpack-chain?
I believe everyone is no stranger to Webpack, the famous build tool in the industry. As the most stable and widely used build and packaging tool in production environment, it certainly has many advantages, such as:
Rich in ecology. There are a lot of loader and plugin in the community, and you can find almost everything you want.
Pluggable plug-in mechanism. Extensible architecture based on Tapable implementation.
The document is mature. There is a Chinese version, and it has been updated and maintained.
High stability. Now the formal front-end project production environment is basically built with Webpack, after so many years of industry verification, the pit to step on is almost enough.
But in fact, after talking about so many advantages, people probably don't like this thing, because there is the most important point that can not be ignored, that is, the development experience. For the matter of building packaging, it is an extremely complex part of engineering, and a large amount of configuration information needs to be entered to ensure that the packaging results meet expectations. In Webpack, if we do not use other solutions, we can only manually configure a huge JavaScript object, and all the configuration information is in this object. This primitive way is really very bad for people, which can be summarized as follows:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
The object is too large, intuitively dazzling, although it can encapsulate some logic, it still can not avoid deep nested configuration.
It is difficult to modify dynamically. For example, if you dynamically modify some configuration information through a script, such as deleting a plugin in babel-loader, you need to find the location of the babel-loader step by step from the top configuration object, and then traverse the plug-in list, which is a tedious process to find and traverse manually.
It is difficult to share configurations. If you try to share webpack configuration objects across projects, subsequent changes will become confusing because you need to modify the original configuration dynamically.
Some people in the community also found these pain points, so there is a streaming configuration scheme for Webpack-webpack-chain.
Core concepts of webpack-chain
In fact, to really learn webpack-chain, I think the first thing is not to learn how to configure each property, but to understand the two core objects of webpack-chain-ChainedMap and ChainedSet.
What is ChainMap?
For example, I now configure path aliases:
Config.resolve.alias .set (key, value) .set (key, value) .delete (key) .clear ()
So, now the alis object is a ChainMap. If an attribute is marked ChainMap in webpack-chain, it has some additional methods and allows these chained calls (such as the example above).
Next, let's learn about these methods one by one:
/ / clear all properties of the current Map clear () / / remove a single configuration from the Map by key value. Whether there is a specific key to configure values in delete (key) / / Map, returns true or false has (key) / / returns an array of values stored in Map values () / / provides an object whose properties and values are mapped to Map. The second parameter is an array indicating which attributes merge (obj, omit) / / handler: ChainedMap = > ChainedMap / / A function batch (handler) / / condition: Boolean / / whenTruthy: ChainMap-> any that takes the ChainedMap instance as a single parameter, execute / / whenFalsy: ChainSet-> any if the condition is true, and execute when (condition, whenTruthy, whenFalsy) / / get the value get (key) / of the corresponding key in Map if the condition is false / call get first If the corresponding value cannot be found, the result getOrCompute (key, fn) / / configuration key-value pair set (key, value) returned by the fn function will be returned.
The return objects of these methods are also ChainMap, which enables chained calls and simplifies operations. In Webpack, most of the objects are ChainMap, you can go to the source code to have a look, the implementation is not complex.
ChainMap is a very important data structure in webpack-chain, which encapsulates the methods of chain calls, so that all subsequent configurations of ChainMap types can directly reuse these methods of ChainMap itself, which is very convenient.
What is ChainSet?
Similar to ChainMap, it encapsulates its own set of API:
/ / add a value add (value) / / add a value prepend (value) / / clear set content clear () / / delete a value delete (value) / / determine whether there is a value has (value) / / return a list of values values () / merge the given array to the end of Set. Merge (arr) / / handler: ChainSet = > ChainSet / / A function batch (handler) / / condition: Boolean / / whenTruthy: ChainSet-> any that takes a ChainSet instance as a single argument, executes / / whenFalsy: ChainSet-> any if the condition is true, and when (condition, whenTruthy, whenFalsy) if the condition is false
The function of ChainSet is similar to ChainMap, it is also an API that encapsulates the underlying chained calls, which can be done by calling the ChainSet method when you need to manipulate the properties of the array type in the Webpack configuration.
Shorthand method
There is a simplified way to write ChainMap, which is called shorthand on the official website:
DevServer.hot (true); / / the above method is equivalent to: devServer.set ('hot', true)
Therefore, in the actual webpack-chain configuration, you can often see directly. Does it feel ingenious to call the attribute () in this way? The implementation in the source code is very simple:
Extend (methods) {this.shorthands = methods; methods.forEach (method = > {this [method] = value = > this.set (method, value);}); return this;}
When ChainMap is initialized, the extend method is called, then the property list is passed in directly as a methods parameter, and then the set method is called indirectly through the following line of code:
This [method] = value = > this.set (method, value)
Such a design is also worth learning.
Configure Webpack
First, you need to create a new configuration object:
Const Config = require ('webpack-chain'); const config = new Config (); / / after a series of chain operations / / get the final webpack object console.log (config.toConfig ())
Then configure resolve, entry, output, module, plugins, optimization objects in turn, the key of this article is to bring you to the ground webpack-chain, so introduce the use of each configuration in detail.
Entry and output
Here is a common configuration. As Webpack has too many attributes in entry and output, please refer to the official Webpack documentation and match it in the following way.
Config.entryPoints.clear () / / empties the default entry config.entry ('entry1'). Add ('. / src/index1.tsx') / / New entry config.entry ('entry2'). Add ('. / src/index2.tsx') / / New entry config.output .path ("dist") .filename ("[name]. [chunkhash] .js") .chunkFilename ("chunks/ [name]) .[ chunkhash] .js ") .libraryTarget (" umd ") alias
The configuration of path aliases is also an essential part of almost all projects, as follows:
/ / you can find that resolve.alias is actually a ChainMap object config.resolve.alias .set ('assets',resolve (' src/assets')) .set ('components',resolve (' src/components')) .set ('static',resolve (' src/static')) .delete ('static') / / delete the specified alias plugins
The configuration of the plug-in can be said to be a very important part. The configuration in webpack-chain will be a little different from the usual configuration. Let's take a look at it in detail.
1. Add a plug-in / / first specify the name (the name is custom), and then add the plug-in config .plugin (name) .use (WebpackPlugin, args) through use
For example:
Const ExtractTextPlugin = require ('extract-text-webpack-plugin'); / / specify the name first (this name can be customized), and then add the plug-in through use. The second parameter of use is the plug-in parameter, which must be an array, or you can not pass config.plugin (' extract') .use (ExtractTextPlugin, [{filename: 'build.min.css', allChunks: true,}]) 2. Remove plug-in
Removing a plug-in is easy. Remember when we added a plug-in that we specified the name for each plug-in? Now you can remove it through this name:
Config.plugins.delete ('extract') 3. Specifies that the plug-in is called before / after the xx plug-in
For example, I now need to specify that the html-webpack-plugin plug-in executes before the extract plug-in I just wrote, so this is fine:
Const htmlWebpackPlugin = require ('html-webpack-plugin'); config.plugin (' html') .use (htmlWebpackPlugin). Before ('extract')
Through the before method, you can pass in the name of another plug-in, indicating that it is executed before another plug-in.
Similarly, if you need to execute after the extract plug-in, call the after method:
Config.plugin ('html'). Use (htmlWebpackPlugin). After (' extract') 4. Dynamically modify plug-in parameters
We can also use webpack-chain to dynamically modify the parameters passed by the plug-in, for example:
Use the tap method to modify the parameter config. Plugin (name). Tap (args = > newArgs) 5. Modify the plug-in initialization process
We can also customize the instantiation process of the plug-in, such as the following:
/ / return an instance through the init method, which will replace the original instantiation process config. Plugin (name) .init ((Plugin, args) = > new Plugin (.. ARGs)); loader
Loader is an essential configuration in Webpack, so let's take a look at the operation of loader.
1. Add a loaderconfig.module .rule (name) .use (name) .loader (loader) .options (options)
For example:
Config.module .rule ('ts') .test (/\ .tsx? /) .use (' ts-loader') .loader ('ts-loader') .options ({transpileOnly: true}) .end () 2. Modify loader parameters
You can modify the parameters of loader through the tap method:
Config.module .rule ('ts') .test (/\ .tsx? /) .use (' ts-loader') .loader ('ts-loader') .tap (option = > {/ / a series of return options;}) .end ()
After all the configuration is complete, you can get the final configuration object by calling config.toConfig (), which can be used directly as the configuration of webpack.
3. Remove a loader// through the delete method of the uses object, and delete the config.module .rule ('ts') .test (/\ .tsx? /) .uses.delete (' ts-loader') optimization according to the name of the loader
Optimization in Webpack is also a relatively large object, refer to the official document: https://webpack.js.org/configuration/optimization/.
Here, take splitChunks and minimizer as examples to configure:
Config.optimization.splitChunks ({chunks: "async", minChunks: 1, / / minimum chunk, default 1 maxAsyncRequests: 5, / / maximum number of asynchronous requests, default 5 maxInitialRequests: 3, / / maximum number of initialization requests Default 3 cacheGroups: {/ / start setting cache chunks priority: 0, / / cache group priority vendor: {/ / key is the entry name defined in entry chunks: "initial", / / you must choose one of three: "initial" | "all" | "async" (default is async) test: / react | vue/, / / regular rule verification If it matches, extract chunk name: "vendor", / / delimited chunk name to cache minSize: 30000, minChunks: 1,}) / / add a minimizer config.optimization.minimizer ('css') .use (OptimizeCSSAssetsPlugin, [{cssProcessorOptions: {}}]) / / remove minimizer config.optimization.minimizers.delete (' css') / / modify the minimizer plug-in parameter config.optimization.minimizer ('css') .tap (args = > [. Args, {cssProcessorOptions: {safe: false}}]) make good use of conditions
As mentioned earlier, the conditional configuration method when for both ChainSet and ChainMap objects can replace if-else in many scenarios, maintaining chained calls to the configuration and making the code more elegant.
Config.when (process.env.NODE = = 'production', config.plugin (' size') .use (SizeLimitPlugin)) so far, I believe you have a better understanding of "how to configure Webpack", so you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.