Advanced concepts

Tree Shaking {a} from ‘./fn.js’ is only supported statically because require(‘./fn.js’) is not allowed statically because it is not required dynamically

How to configure, production is enabled by default, development mode needs to configure vue.config.js: Optimization :{usedExports:true} sideEffects:false If special processing is required without traashaking, do the following configuration

In package.json you also need to configure sideEffects:[‘@babel/poly-fill’]. If you don’t configure it, a package like babel-Polyfill doesn’t export anything, it binds things to Windows. Tree shaking will take care of it. To avoid this, configure sideEffects:[‘@babel/poly-fill’]

Import ‘./a.css’ does not export things when importing CSS files, which will also be processed, so package.json should be written as sideEffects:[‘*.css’]

In fact, in development mode, even Tree Shaking does not remove excess code directly. Instead, it identifies it as unused, but it removes production

Second point: mode development and production

In production mode, code is usually compressed, and source-map can generate map files. In order to avoid the trouble of switching between the two modes frequently, the original webpack.config.js file can be divided into two, webpack.dev.js and webpack.prod.js. Json ‘dev’ :’webpack-dev-server –config webpack.dev.js’,

‘build’:’webpack –config webpack.prod.js’

SplitChunksPlugin splitChunks: {} So the default configuration is splitChunks: {

MinRemainingSize: 0, maxSize: 0, minRemainingSize: 0, minRemainingSize: 0 1, maxAsyncRequests: 30, maxInitialRequests: 30, enforceSizeThreshold: 50000, cacheGroups: { defaultVendors: { test: /[\\/]node_modules[\\/]/, priority: -10, reuseExistingChunk: true }, default: { minChunks: 2, priority: -20, reuseExistingChunk: true } } }Copy the code

Optimization :{splitChunks:{chunks:’all’,

}
Copy the code

} all indicates synchronous and asynchronous splitting, async indicates asynchronous file splitting, and INITIAL indicates synchronous band splitting

In fact asynchrony is automatically packaged into a separate file function a() {

return import(/* webpackChunkName=”lodash” */ ‘lodash’).then((default:’_’)=>{

_.join(['1','2'])
Copy the code

})

}

a()

/webpackChunkName=”lodash” But this only works if the Babel dynamic import function uses the official plugin @babel/plugin-syntax-dynamic-import, which requires the plugins in the babelrc file to be configured accordingly

Fourth point: Lazy loading and chunk lazy loading are not necessarily bound to Webpack, it is related to es6 import concept, so to use lazy loading, must use Babel-Polyfill

In terms of chunk, each JS file is a chunk and can be regarded as a chunk. MinChunks: 3 in the preceding code segmentation configuration means that the chunk referenced will be extracted and segmented as a common JS only after being referenced for at least three times

Fifth point: Package analysis, preload prefetch

Packaging analysis: Webpack –profile –json > a.json –config common.config.js means that the data related to the packaging process will be put into this JSON file, Then the webpack.github.com/analyse website has a tool can analyze the file, tools are many, in addition to the official, also, There is a bundle analysis TAB under Code Splitting in the guides website of Webpack. There are many of them. Choose your own bundle analysis

For preload, think of splitchunks in WebPack to configure chunks: The default is async, not all, why? Because for synchronous code, after splitting, the effect is only used for the second time do not load, but webPack wants to have the effect for the first time. We can analyze the page, use CTRL + Shift + P command in the console, type show coverage, click refresh. You can see the performance analysis of the files loaded at the beginning of the page

To implement file preload document. AddEventListener (” click “, () = > {

import(/* webpackPrefetch:true */, ‘./a.js’).then(({default:f}) => { f() })

} webpack believes that the real performance improvement is asynchronous load file, synchronous use of cache is not essential, with prefetch and preload is the best, but what is the difference between prefetch and preload? Prefetch is used to load the main file when it is free, but preload is loaded at the same time as the main file, so it is best to use prefetch.

!!!!! Just remember, caching is not the most important thing to improve performance, it’s about improving code utilization !!!!!

Sixth: CSS file code segmentation can use the MiniCssExtractPlugin, this plug-in does not support HMR hot update, so it is best to use in the production environment, there is a supporting plug-in compression CSS

Number seven: Webpack and browser caching

If the file name is unchanged, the user will normally refresh (but not force refresh) the browser cache file and will not look for the latest server file. For this reason, the production environment in output should be name: [name].[contenthash].js The latest webPack5 content is unchanged. RuntimeChunk :{name:runtime}}; runtimeChunk:{name:runtime}; runtimeChunk:{name:runtime}

Number eight: Shimming Webpac packages code that doesn’t work on some of the lower versions of browsers, so he will help us make it compatible

Index.js: import $from ‘jquery’ import {b} from ‘a.js’s (‘body’)……

a.js: export function b(){ $(‘#ee’)…. }

At this time, the third-party library A has not introduced jquery. If you use it directly in index.js, an error will be reported, but we cannot directly change the code of A. Plugins :[new webpack.provideplugin ({:’jquery’})] [plugins:[new webpack.provideplugin ({:’jquery’})]

In any other module, this points to the module itself, not the window. If you want this to point to the window, use the imports- Loader

# 9: Environment variables using webpack.config.js:

module.exports=(env)=>{

if(env&&env.production){

return{}
Copy the code

}else{

reutrn {}

}

}

So in package.json: scripts:{

build: webpack –env.production –config ‘./webpack.common.js’ }

Production = ABC –config ‘./webpack.common.js’ then if(env&&env.production=== ‘ABC’)

# 10: Loaders and plugins

Loader is a function that accepts a string buffer, and set up the module. Exports. The raw = true can accept data buffer type, the execution of the loader into the pitch and normal, pitch is once upon a time in the future and then after the execution of normal forward, The third parameter of pitch, data, can be obtained in the normal stage. If there is return data in the pitch stage, it will directly skip the following loader and execute it directly in the previous one. Loader can be synchronized or asynchronous

Plugin is a class in which WebPack implements the apply method. The default compiler parameter is Compiler.hooks. Emit. Tap (‘ Plug-in name ‘,(compilation)=>{compilation can go to the current execution stage of the package})

Compiler hooks are similar to the lifecycle of a VUE and can do whatever they want at the stage they want, Specific hooks to see website commonly used API htmlWebpackPlugin, cleanWebpackPlugin, miniCssExtractPlugin, DllPlugin,