Js files are loaded on demand
Without this setting, the first screen of the project will load all the JS files of the entire site, so it is a good optimization method to disassemble the JS files and load the JS files of that page when you click on it. Lazy loading of vUE components is used here. In router.js, instead of using the import method to import components, use require.ensure.
import index from '@/components/index'
const index = r= > require.ensure([],() = > r(require('@/components/index'),'index'))
// If the second argument is written, package it into the file named JS/index
// If the second argument is not written, it is packaged directly in the 'JS' directory.
const index = r= > require.ensure([],() = > r(require('@/components/index')))
Copy the code
The html-webpack-plugin places the JS file at the end of the body
By default, in index.html after build, js is added in the head. Use the html-webpack-plugin to change the inject value to body. You can put js at the end of the body.
var HtmlWebpackPlugin = require('html-webpack-plugin');
new HtmlWebpackPlugin({
inject:'body'
})
Copy the code
Externals use CDN
For example, vuex, VUE-Router and other plug-ins in the project are directly introduced into index.html using the domestic BOOtcDN, and externals is added in webpack, ignoring libraries that do not need to be packaged
module.exports = {
context: path.resolve(__dirname, '.. / '),
entry: {
app: './src/main.js'
},
externals: {'vue':'Vue'.'vue-router':'VueRouter'.'vuex':'Vuex'
},
Copy the code
Webpack Bundle Analyzer
We can use the WebPack visualization plugin WebPack Bundle Analyzer to look at project JS file sizes, and then purposefully resolve oversized JS files. The installation
npm install –save-dev webpack-bundle-analyzer
Set the following in Webpack, and NPM run dev will be opened in the browser by default
const BundleAnalyzerPlugin = require(‘webpack-bundle-analyzer’).BundleAnalyzerPlugin;
module.exports = { plugins: [ new BundleAnalyzerPlugin() ] }
Use the UglifyJsPlugin plug-in to compress the code and remove the console
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false.drop_console:true.pure_funcs: ['console.log']}},sourceMap: config.build.productionSourceMap,
parallel: true
}),
Copy the code