Vue inspect to view the default Webpack configuration information for the current project (important)
Plug-in address: www.webpackjs.com/plugins/
Compression -webpack-plugin Enables Gzip compression
1. The function of compression-webpack-plugin
Effect: Improve the network transmission rate => Optimize the Web page loading time
Files can be pre-gzip compressed with the help of the CompressionWebpackPlugin.
In this way, the server directly reads. Gz files with the same name as the source file, and does not compress them actively, reducing the CPU load and optimizing the server performance.
* Fundamentals
1) When the browser requests resource files, it will automatically bring an Accept-encoding header to tell the server the supported compression Encoding type;
2) Server configuration enable gzip option: When receiving a request for resource files from the client, check the content-encoding format supported by the request header. If the request contains gzip, the resource file is returned after the gzip encoding is performed (Content-encoding: gzip is included in the response header).
3) The browser receives the response and checks whether the request header contains Content-encoding:gzip. If so, decompress the returned resource file and parse the rendering.
2. Use of compression-webpack-plugin project
1. Install compression-webpack-plugin
npm install compression-webpack-plugin --save-dev
Copy the code
* NPM address: www.npmjs.com/package/com…
2. Vue.config. js configuration of vuE-cli3
const CompressionWebpackPlugin = require('compression-webpack-plugin'); Module.exports = {// Set some webPack config items and merge configureWebpack with default config items: {plugins: [new CompressionWebpackPlugin({// change the configuration item of 1.x to filename filename: Info => '${info.path}. Gz ${info.query} ', // 10240, / / compression test data of more than 10.24 k: new RegExp (` \ \. (${[' js]. Join (' | ')}) $`), matching filename / / / / test: New RegExp (' (' + [' js', 'CSS']. Join (' | ') + ') $'), minRatio: 0.8, / / compression ratio deleteOriginalAssets: false, / / not to delete the source file]}}})Copy the code
Two, image-webpack-loader image compression use
1. Image-webpack-loader functions
Using image compression (PNG, JPEG, GIF, SVG, and WEBP) in WebPack can greatly reduce package sizes and is an important optimization point for the front end.
Image-webpack-loader is recommended, as well as img-loader and imagemin-webpack-plugin. In fact, the underlying call excuses are similar.
2. Use image-webpack-loader project
** Install image-webpack-loader
npm install image-webpack-loader --save-dev
Copy the code
* NPM address: www.npmjs.com/package/ima…
**2, **Vue-cli3 vue.config.js configuration
Module.exports = {// Go directly to the built-in webpack configuration item chainWebpack: (config) => {config.module. rule('images').use('image-webpack-loader').loader('image-webpack-loader'). .options({ bypassOnDebug: true, }) .end(); }}Copy the code
2. Problems encountered
Image-webpack-loader cannot be installed or is stuck. After the installation, the image-webpack-loader is stuck and does not move for half a day.
* Summary problem: package installation problem, NPM download down because of the wall problem, package download is not complete (problem will appear)
3. Solutions
Procedure method 1 :(win operation)
1. If image-webpack-loader has been installed, uninstall it first
npm uninstall image-webpack-loader
Copy the code
2. Use CNPM. This step means to install CNPM and set the global Registry as the mirror of Ali
npm install cnpm -g --registry=https://registry.npm.taobao.org
Copy the code
3. Install image-webpack-loader using CNPM and you will find it installed quickly
cnpm install --save-dev image-webpack-loader
Copy the code
Method 2 :(Mac operation)
1. Drop package.json for now. For example: “image-webpack-loader”: “^7.0.1”
Vue. Config. js comments the code
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({
bypassOnDebug: true,
})
.end();
Copy the code
3. After the package is installed successfully, CNPM installs image-webpack-loader and resumes vue. Config. js
sudo cnpm install image-webpack-loader --save-dev
Copy the code
3, uglifyjs-webpack-plugin code compression, delete console and annotations
1. Uglifyjs-webpack-plugin
UglifyJsPlugin is used to compress JS files and reduce the size of JS files. It will slow down the compilation of WebPack. It is recommended that you turn it off in development and turn it on in production.
2. Use uglifyjs-Webpack-plugin project
Install uglifyjs-webpack-plugin
npm install uglifyjs-webpack-plugin --save-dev
Copy the code
* NPM address: www.npmjs.com/package/ugl…
2. Vue.config. js configuration of vuE-cli3
const UglifyPlugin = require('uglifyjs-webpack-plugin'); optimization: { minimizer: [ new UglifyPlugin({ uglifyOptions: {// delete comments output:{comments:false}, // delete console True,//console drop_debugger: false, pure_funcs: ['console.log']// Remove console}}})]}Copy the code
Configure proxy to forward devserver. proxy
1. Function of devServer.proxy
Cross-domain processing. Cross-domain indicates that the url of any protocol, domain name, or port is different from that of the current page.
2. Devserver. proxy project
DevServer: {// match rule open: false, // automatically start browser host: '0.0.0.0', // localhost port: 6060, // port number HTTPS: false, hotOnly: False, // hot update proxy: {'/ API ': {target: "https://www.baidu.cn/", // cross domain url ws: true, // enable WebSocket Secure: ChangeOrigin: true, // // automatically changes the host pathRewrite in the HTTP header: {"^/ API ": "", // Path replacement rule}}}}Copy the code
**pathRewrite: If you do not write the proxy, you can change only the proxy domain name. If you write the proxy, you can change the proxy domain name and the following path.
Pack only changed files
Install NPM I webpack -d
const { HashedModuleIdsPlugin } = require('webpack');
configureWebpack: config => {
const plugins = [];
plugins.push(
new HashedModuleIdsPlugin()
)
}
Copy the code
6. Enable package log analysis
Install NPM I webpack-bundle-Analyzer -d
chainWebpack: config => {
config
.plugin('webpack-bundle-analyzer')
.use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
}
Copy the code
Vii. Complete configuration of vue.config.js architecture (for reference)
const path = require('path'); Const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const CompressionWebpackPlugin = require('compression-webpack-plugin'); Const {HashedModuleIdsPlugin} = require('webpack'); function resolve(dir) { return path.join(__dirname, dir) } const isProduction = process.env.NODE_ENV === 'production'; // CDN preload using const externals = {'vue': 'vue', 'vue-router': 'VueRouter', 'vuex': 'vuex', 'axios': 'axios', "element-ui": "element "} const CDN = {// dev dev: {CSS: [' https://unpkg.com/element-ui/lib/theme-chalk/index.css '], js: []}, / / production environment build: {CSS: [ 'https://unpkg.com/element-ui/lib/theme-chalk/index.css' ], js: [' https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-router.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vuex.min.js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js', 'https://unpkg.com/element-ui/lib/index.js' ] } } module.exports = { lintOnSave: False, // Disable esLint productionSourceMap: false, publicPath: './', outputDir: Process.env.outputdir, // Generate file directory name chainWebpack: config => { config.resolve.alias .set('@', Resolve (' SRC ')) / / compressed picture config. The module. The rule (' images'). The test (/ \. (PNG | jpe? G | | GIF SVG) (\? *)? $/) .use('image-webpack-loader') .loader('image-webpack-loader') .options({ bypassOnDebug: // Webpack will ring chunk-vendors to commonChunk by default, So I need to delete webpack configuration config. The optimization. The delete (' splitChunks) config. The plugin (' HTML '). The tap (args = > {the if (process.env.NODE_ENV === 'production') { args[0].cdn = cdn.build } if (process.env.NODE_ENV === 'development') { args[0].cdn = cdn.dev } return args }) config .plugin('webpack-bundle-analyzer') .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin) }, configureWebpack: config => { const plugins = []; If (isProduction) {plugins.push(new UglifyJsPlugin({uglifyOptions: {output: {comments: false, // remove comments}, warnings: false, compress: { drop_console: true, drop_debugger: false, pure_funcs: ['console.log']// Remove console}}})) // Server to enable gzip plugins.push(new CompressionWebpackPlugin({algorithm: 'gzip, test: / \. (js) | CSS $/, / / matching filename threshold: 10000, the data of more than 10 k / / compression deleteOriginalAssets: false, / / not to delete the source file minRatio: 0.8 // compression ratio})) // Used to generate hash as module ID based on the relative path of the module, Plugins.push (new HashedModuleIdsPlugin()) // Enable separation js config.optimization = {runtimeChunk: 'single', splitChunks: { chunks: 'all', maxInitialRequests: Infinity, minSize: 1000 * 60, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, Name (module) {// exclude node_modules and replace @ with null, considering server compatibility const packageName = module.context.match(/[\\/]node_modules[\\/](.*?) ([\\/]|$)/)[1] return `npm.${packageName.replace('@', '')}` } } } } }; Config. performance = {hints: 'Warning ', // maxEntrypointSize: 1000 * 500, // The maximum size of the generated file maxAssetSize: 1000 * 1000, function (assetFilename) { return assetFilename.endsWith('.js'); Externals = externals; externals = externals; } return {plugins}}, pluginOptions: {// configure global less' style-resources-loader': {preProcessor: 'less', patterns: [resolve('./ SRC /style/theme. Less ')]}}, devServer: {open: false, // start browser host: '0.0.0.0', // localhost port: // Update proxy: {'^/sso': {target: process.env.vue_app_sso, // override path ws: True, // Enable WebSocket Secure: false, // For HTTPS interfaces, you need to configure this parameter changeOrigin: true}}}}Copy the code