Webpack4.0 new features
This section describes new webPackage 4.0 features
Package optimization strategy
- Webpackage 4.0 Packaging Optimization Strategy (I)
- Webpackage 4.0 Packaging Optimization Strategy (II)
- Webpackage 4.0 Packaging Optimization Strategy (iii)
The current version of the dependent package
1. Optimize loader configuration
1.1 Narrowing the File Matching Range (include/ Exclude)
By excluding files under node_modules, the loader can narrow the search scope of files with high probability of hitting
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader', exclude: /node_modules/, // exclude: /node_modules/, // include: path.resolve(__dirname,'src') // Specify exactly which directory to process}]}Copy the code
1.2 Execution Result of Caching Loader (cacheDirectory)
CacheDirectory is a loader-specific option with a default value of false. The specified directory (use: ‘babel-loader? CacheDirectory =cacheLoader’) will be used to cacheLoader execution results and reduce Babel recompilation when webpack is built. If a null value is set (use: ‘babel-loader? CacheDirectory ‘) or true (use: ‘Babel – loader? CacheDirectory =true’) will use the default cache directory (node_modules/.cache/babel-loader), and if the node_modules directory is not found in any root directory, it will be demoted back to the default temporary file directory of the operating system.
Babel-loader is very slow!
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader? cacheDirectory'Exclude: /node_modules/, include: path.resolve(__dirname,'src')}}]Copy the code
2. Resolve Optimize the configuration
2.1 Optimize the module search path resolve.modules
Resolve. Modules configuration module library (node_modules) in Webpack. Import ‘vue’ in JS is not a relative or absolute path, so node_modules will look in node_modules. The default configuration, however, uses the upward recursive search, but usually there is only one node_modules in the project directory, and it is in the root directory of the project. To reduce the search scope, you can directly specify the full path of node_modules. The same is true for aliases:
const path = require('path');
functionResolve (dir) {// Convert to an absolute pathreturnpath.join(__dirname, dir); } resolve: {modules: [//'src'),
path.resolve('node_modules') // specify the node_modules location to search from when you import third-party modules]}Copy the code
After the SRC directory is configured, the util directory is inside SRC, so you can import utility functions in util as follows
// main.js
import dep1 from 'util/dep1';
import add from 'util/add';
Copy the code
2.2 resolve.alias Configure the path alias
Create a path alias for import or require to make module import easier. Configuration items map the old import path to a new import path by alias this optimization affects the use of tree-shaking to remove invalid code
For example, some common modules are located in the SRC/folder:
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/')}Copy the code
Now, replace the “use relative paths when importing” approach like this:
import Utility from '.. /.. /utilities/utility';
Copy the code
You can use aliases like this:
import Utility from 'Utilities/utility';
Copy the code
resolve: {
aliasAlias configuration: {// alias configuration allows us to make references simple'vue$': 'vue/dist/vue.common.js'SRC: resolve()'src') // You can import moduleA from whenever you need to import files under SRC'src/moduleA'SRC will be replaced with resolve('src'Return absolute path without relative path import}}Copy the code
You can also add $to the end of a given object’s key to indicate an exact match:
alias: {
util$: resolve('src/util/add.js')}Copy the code
This will produce the following results:
import Test1 from 'util'; SRC /util/add.js is parsed and imported import Test2 from'util/dep1.js'; Util /dep1.jsCopy the code
2.3 resolve. Extensions
When modules are imported without file suffixes WebPack automatically resolves the file suffixes identified based on this configuration
- Keep the suffix list as small as possible
- Let’s put the highest frequency forward
- Export statements are suffixed whenever possible
resolve: {
extensions: ['.js'.'.vue']}Copy the code
3.module.noParse
Modules using noParse will not be parsed by loaders, so if we use a library that is too large and does not contain calls to import require and define, We can use this configuration to improve performance and make Webpack ignore recursive parsing of files that are not modularized.
/ / ignore the jquery lodash recursively parsing module: {/ / noParse: / jquery | lodash / / / from webpack 3.0.0 started noParse:function(content) {
return /jquery|lodash/.test(content)
}
}
Copy the code
4.HappyPack
HappyPack allows Webpack to extend loader execution from a single process to a multi-process mode, that is, to divide tasks into multiple sub-processes for concurrent execution, and then send the results to the main process after the sub-processes finish processing. This speeds up code construction and is best used in conjunction with DLL dynamic link libraries.
npm i happypack@next -D
Copy the code
webpack.config.js
const HappyPack = require('happypack');
const os = require('os'); Const happyThreadPool = happypack.threadpool ({size: 1, 0, 0, 0, 0); // Node provides system operation module // Specifies the number of thread pools according to the number of cores on my system. os.cpus().length}) module: { rules: [ {test: /\.js$/,
use: 'happypack/loader? id=babel',
exclude: /node_modules/,
include: path.resolve(__dirname, 'src'}]}, plugins: [new HappyPack({// base parameter id:'babel'// loader? The following id loaders: ['babel-loader? cacheDirectory'], // Loader threadPool: happyThreadPool, // cache:true// deprecated verbose:true
});
]
Copy the code
Loader provided by Happypack is the loader that handles the actual file matching. Here happypack provides loader and plugin connection matching, is completed by id=happypack. Happypack principle analysis – Taobao front end
npm run dev
Copy the code
DLL Dynamic link library
A dynamically linked library can contain functions and data called by other modules. The dynamically linked library only needs to be compiled once, and modules included in the dynamically linked library will not be recompiled later in the build process, but will use the code in the dynamically linked library directly.
- Take the base modules that web applications depend on and package them into a separate dynamically linked library. A linked library can contain multiple modules.
- When a module to be imported exists in a dynamically linked library, the module is not packaged again, but retrieved from the dynamically linked library.
- All dynamic link libraries that the page depends on need to be loaded.
5.1 Defining DLL Configurations
Depend on two built-in plug-ins: DllPlugin and DllReferencePlugin
5.1.1 Creating a DLL configuration file webpack_dll.config.js
module.exports = {
entry: {
react: ['react'.'react-dom']
},
output: {
filename: '[name].dll.js'Path: path.join(__dirname,'dist'), // Dynamic link library output path libraryTarget:'var', // Link library (react.dll. Js) output mode default'var'The form is assigned to the variable B library:'_dll_[name]_[hash]'}, plugins: [new webpack.DllPlugin({// path specifies the output path of the manifest file: path.join(__dirname,'dist'.'[name].manifest.json'),
name: '_dll_[name]_[hash]'Manifest.json})]}Copy the code
5.1.2 output.libraryTarget specifies which way to export your library as a global variable by default
It includes the following:
-
“Var” – direct variable output (default library) var library = XXX (default)
-
“This” – Prints this[“Library”] = XXX by setting this property
-
“Commonjs” – exports[“Library”] = XXX by setting exports property
-
“Commonjs2” – exports module.exports = XXX by setting module.exports property
-
“Amd” – Output as AMD
-
“Umd” – combine commonJs2 / AMD /root
5.1.3 Packaging to generate a Dynamic link library
webpack --config webpack_dll.config.js --mode production
Copy the code
- The react.dll. Js dynamic link library contains react and react-dom contents
- React. Manifest.json describes information in the link library (react. DLL)
5.2 Using the Dynamic Link Library file in the Main Configuration File
// webpack.config.js
const webpack = require('webpack'); plugins: [/ / when we need to use dynamic link library First find the manifest file to get the name value record global variable name And then find the dynamic link library file to load new webpack. DllReferencePlugin ({manifest: require ('./dist/react.manifest.json')})]Copy the code
5.3 Loading the Dynamic Link Library file to the Page
Two WebPack plug-ins are required
- Html-webpack-plugin produces HTML files
- Html-webpack-include-assets-plugin Adds JS CSS resources to HTML to extend the functions of HTML plug-ins
npm i html-webpack-plugin html-webpack-include-assets-plugin -D
Copy the code
Configuration webpack. Config. Js
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlIncludeAssetsPlugin = require('html-webpack-include-assets-plugin');
pluings: [
new webpack.DllReferencePlugin({
manifest: require('./dist/react.manifest.json')
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src/index.html')
}),
new HtmlIncludeAssetsPlugin({
assets: ['./react.dll.js'], // Add resource relative to HTML path append:false // falseAdd before any other resourcetrueAdd}) after other resources; ]Copy the code
At this point, react.dll.js and main.js are automatically introduced to the page, and the DLL file is loaded before main.js
6.ParallelUglifyPlugin
This plug-in can help speed up builds for projects with many entry points. Change the serial compression of JS files to uglify in parallel by enabling multiple subprocesses.
cnpm i webpack-parallel-uglify-plugin -D
Copy the code
// webpck.config.js
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
plugins: [
new ParallelUglifyPlugin({
workerCount: 4,
uglifyJS: {
output: {
beautify: false// No need to format comments:false// Keep comments}, compress: {// compress warnings:false// Drop useless code without warning drop_console:trueCollapse_vars: // Collapse the console statement collapse_vars:true// Inline variable reduce_vars that are defined but used only once:true// Extract static values that occur multiple times but are not defined as variables to reference}}}); ]Copy the code
compression
webpack --mode production
Copy the code
7.Tree Shaking
Eliminate code that doesn’t work in JavaScript. It relies on static ES6 modularity syntax, such as import and export via impot and export
CommonJS modules are different from ES6 modules
CommonJS modules:
-
1. Dynamic loading module commonJS is easy to implement lazy loading and optimize the user experience
-
2. Load the whole module. In commonJS module, export the whole module
-
3. Every module is an object commonJS modules are treated as an object
-
CommonJS module output is similar to function value passing and is worth copying
Es6 module
-
1. Static parsing of ES6 modules loading at compile time means that the dependency of the output modules is determined at the parsing stage, so the import of ES6 modules is generally written at the beginning of the introduced file
-
Modules are not objects In ES6, each module is not treated as an object
-
3. Not the whole module Is loaded. In the ES6 module, there are several exports in one module
-
4. Reference to a module In es6, you export the reference of the module rather than the copy of the module
7.1 Retain the ES6 modular syntax
// .babelrc
{
"presets": [["env", {
modules: false// Do not compile the ES6 module},"react"."stage-0"]]}Copy the code
7.2 Executing Production Compilation Tree Shaking is enabled by default
webpack --mode production
Copy the code
What is Tree Shaking?
There is a funs.js that has two functions in it
// funs.js
export const sub = () => 'hello webpack! ';
export const mul = () => 'hello shaking! ';
Copy the code
Funs.js is a dependency in main.js
// main.js
import {sub} from './funs.js'
sub();
Copy the code
If main.js only uses the sub function in funs.js, by default it also packages other functions that are not in funs.js, if tree shaking is turned on at compile time
Webpack --mode production // The unused funs.js code is not packaged and removedCopy the code
The next chapterWebpackage 4.0 Packaging Optimization Strategy Sorting (II)
- To distinguish the environment
- Extract common generation
- The separation
- Open the Scope Hoisting
Source reference
Making the source code
reference
- Webpack often uses configuration splitting
- Webpack official loaders documentation