Narrow down your search for files
Optimizing loader Configuration
There are three configuration items to narrow the scope of loader processing:
- Include: include modules that meet any of the following criteria, i.e., which modules to search for precisely (officially recommended)
- Exclude: excludes all matching modules
Include and exclude can be strings, arrays, and even functions, regules, and objects.
Example:
include: path.resolve(__dirname, "./src"),
include: [
path.resolve(__dirname, 'app/styles'),
path.resolve(__dirname, 'vendor/styles'),
],
Copy the code
resolve
resolve.alias
Resolve. Alias configures the alias to map the original import path to a new one.
resolve: {
alias: {
"@": path.resolve(__dirname, "./src/"),
}
}
Copy the code
Note: when using HTML, CSS, you need to add ~
background: url(~@/imgs/1.jpg); // Be careful not to use quotesCopy the code
Js:
import '@/styles/index.less';
Copy the code
resolve.modules
Resolve. modules is used to configure the directory in which webpack will look for third-party modules. The default directory is node_modules in the current project directory. Node_modules is no longer searched in the parent directory, and so on, similar to node.js’ module search mechanism.
If our third party modules are installed in the project root directory, we can specify this path directly.
Module.exports ={XXXXX, resolve:{// define the location of third-party dependencies, support single and multiple // modules: path.resolve(__dirname, "./node_modules") modules: [path.resolve(__dirname, "./node_modules")] } }Copy the code
resolve.extensions
When the extensions import statements without suffixes, WebPack automatically suffixes them to try to find out if the file exists. The default values are.js and.json.
extensions: ['.js', '.json', '.ts', '.jsx']
Copy the code
Note:
- The more values in the list, the longer it will take to match, because every file that leaves out the suffix will be suffixed one by one and then checked for its existence, so try to apply the suffix as often as possible.
- When the suffix is omitted, the system will search from left to right. When the a.js meets the conditions, the match will end and the match will not continue, even if the A.ts also meets.
Compressed HTML
New htmlWebpackPlugin({template: "./ SRC /index.html", filename: "index.html", minify: {// Compress removeComments: CollapseWhitespace: true minifyCSS: true // Collapse inline CSS}})Copy the code
Separating CSS files
mini-css-extract-plugin
As mentioned earlier, style-loader is designed to dynamically generate CSS from JS and package it directly into JS, but we want to generate CSS files separately, because this can be downloaded in parallel with JS to improve page loading efficiency, but the drawback is that it will increase requests.
download
npm i mini-css-extract-plugin -D
Copy the code
The introduction of
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
Copy the code
Configured to use
module.exports = {
module: {
rules: [
/ / packaging CSS
{
// test is used to configure the file name that the current packaging rule matches
test: /\.less$/.// use Used to configure the loader used by the current packaging rule
/ / use MiniCssExtractPlugin. Loader to replace style - loader
// It is important to note, however, that after the CSS is removed from the folder, the reference hierarchy issues, need to use.. /
// use: [ MiniCssExtractPlugin.loader, 'css-loader', "postcss-loader", 'less-loader'],
use: [ {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '.. / '}},'css-loader'."postcss-loader".'less-loader'].// include is used to introduce modules that meet any of the following criteria
include: path.resolve(__dirname, './src')},]},plugins: [
new MiniCssExtractPlugin({
filename: "css/[name]_[contenthash:4].css".chunkFilename: "[id].css"}})]Copy the code
Compress CSS
- Cssnano: is a Node-based reductor and postCSS plug-in that can be added to the build process to ensure that the resulting CSS stylesheet file for production is as small as possible.
- optimize-css-assets-webpack-plugin
Installation:
NPM I [email protected] [email protected] -d // Webpack4.x requires both versions 4.0, otherwise cssnano.process will report an errorCopy the code
Introduction:
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
Copy the code
Use:
new OptimizeCSSAssetsPlugin({ assetNameRegExp: /\.css$/g, // This plugin compresses the CSS file output by the mini-css-extract-plugin, not the CSS source file cssProcessor: Require ("cssnano"), // compress the CSS processor, return the Promise object cssProcessorOptions: DiscardComments: {removeAll: true}}, canPrint: true // configuredwhether the plugin canPrint messages to the console})Copy the code
Tree Shaking Removes useless CSS and JS
Tree Shaking is often used to describe static deconstruction features such as import and export that rely on the ES2015 module syntax to remove dead-code from a JavaScript context. This term and concept was actually popularized by the ES2015 module packaging tool rollup. Webpack 4, tagged with the “sideEffects” property of package.json, provides compiler with hints as to which files in the project are “pure “so that unused portions of the file can be safely removed.
The official address
Note: Develpoment tree shaking is not valid if mode is production because Webpack is for debugging.
css tree shaking
Installation:
npm i purify-css purifycss-webpack glob-all -D
Copy the code
Use:
const PurifyCSS = require('purifycss-webpack'); const glob = require('glob-all'); Plugins: [// XXXXX new PurifyCSS({// Remove CSS paths: Resolve (__dirname, './ SRC /*.html'), // We also need to clear the HTML file path.resolve(__dirname, './src/*.js') ]) }) ],Copy the code
JS tree shaking
Note: Only import is supported, not CommonJS, so you need to make sure that no compiler converts ES6 module syntax to CommonJS.
//webpack.config.js optimization: {usedExports: true}Copy the code
sideEffects
If none of the code contains Side Effect, you can simply mark this property as false to tell WebPack that it can safely remove the unused export.
// In package.json: "sideEffects":false // Tree shaking for all modules, only in production mode, usedExports is requiredCopy the code
Official sideEffects and usedExports:
But then all imported files are affected by Tree shaking. This means that if you use something like CSS-Loader in your project and import a CSS file, you need to add it to the Side Effect list to avoid accidentally removing it in production mode. That is, if the code does have some side effects, you can provide an array instead:
/ / package. The json: "sideEffects" : [" * * *. / CSS "and" / *. * * SCSS ", ". / esnext/index. Js ", ". / esnext/configure. Js "].Copy the code
Scope lifting
In this case, webpack uses static analysis of ES6 syntax to analyze the dependency relation between modules and try to place modules in the same function. This makes packaged code files smaller and faster.
Usage:
Optimization: {concatenateModules: true // Start Scope collieries}Copy the code
Function:
Such as:
// a.js export default 'hey hey hey '; // index.js import a from './a.js'; console.log(a);Copy the code
After configuring Scope compensation, we can find that the contents of A.js and index.js are merged together after packaging.
The code of cutting
split-chunks-plugin
When we finish packing and only generate one bundleJs, the code may be too bulky and take too long to download. Webpack provides a convenient way to implement code splitting:
Official Address:
Description of configuration items:
Optimization: {splitChunks: {chunks: 'all',// async (default) initial // maxSize: 0 when modules are larger than 20KB, minChunks: 1 is not recommended. // maxAsyncRequests include: 30,// maxInitialRequests: 30,// maxInitialRequests: 30,// maxInitialRequests: 30,// maxInitialRequests: 30,// automaticNameDelimiter: '-',// True,// packaged names cacheGroups: {// cacheGroups defaultgroups: {test: /[\\/]node_modules[\\/]/, name: "DefaultVendors ", // The names of the separated chunks to be cached priority: -10,// The greater the number of cache group priorities, the higher the precedence reuseExistingChunk: true// Whether the chunk is reused}, other: {chunks: "initial". / / initial | | all async (default) test: / react | lodash /, / / verify the regular rules, if conform to extract the chunk, name: "Other ",// The name of the chunk to be cached and separated minSize: 20000,// The minimum size, if the chunks are larger than 20KB minChunks: 1,// the minimum number of chunks to be packed refers to the chunks}, default: {minChunks: 2,// At least a few chunks of the chunks to be packed reference this module priority: -20,// the larger the priority number, the higher the priority. True // Whether to reuse the chunk}}}}Copy the code
A succinct way to help us do automatic code splitting:
optimization:{
splitChunks:{
chunks:"all"
}
}
Copy the code
The compressed image
Installation :(CNPM is recommended. Yarn and NPM are not completely downloadable.)
cnpm install image-webpack-loader -D
Copy the code
Use:
rules: [{ test: /\.(gif|png|jpe?g|svg)$/i, use: [ 'file-loader', { loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true, }, // optipng.enabled: false will disable optipng optipng: { enabled: false, }, pngquant: {quality: [0.65, 0.90], speed: 4}, GIFsicle: {interlaced: false,}, // The webp option will enable webp webp: { quality: 75 } } }, ], }]Copy the code
The official address
Matters needing attention:
-
Some OSX systems may report an error:
The Module build failed: Error: dyld: Library not the loaded: / usr/local/opt/libpng/lib/libpng16.16 dylibCopy the code
At this point, you need to climb over the wall and install libpng
brew install libpng Copy the code
-
If Cannot find module ‘mozjpeg’, Cannot find module gifsicle, etc., is downloaded dependency incomplete, delete node_modules, use CNPM I to download dependency again.
The code address
Github address: