Vue-cli project optimization to shorten the loading time of the first screen (1)

The project requirements of the recent internship are not very demanding, so I learned to optimize the project, mainly because the loading of the first screen is too slow.

Large file location

We can use the webpack visualization plugin to Webpack Bundle Analyzer view the size of the project js file, and then purposefully solve the oversized js file. 
Install

npm install --save-dev webpack-bundle-analyzer

The settings in webpack are as follows, and then npm run dev it will be displayed on port 8888 by default.

JS files are loaded on demand

Without this setting, all JS files of the entire website will be loaded when the first screen of the project is loaded, so it is a good optimization method to disassemble the JS files and load the JS of the page when clicking on a certain page. 
What is used here is the lazy loading of vue components. In router.js, do not use the import method to import components, use require.ensure.

import index from '@/components/index'
const  index = r => require.ensure( [], () => r (require('@/components/index'),'index'))
//如果写了第二个参数,就打包到该`/JS/index` 的文件中。
//不写第二个参数,就直接打包在`/JS` 目录下。
const  index = r => require.ensure( [], () => r (require('@/components/index')))

use cdn

When packaging, the vue, vuex, vue-router, axios, etc., are directly introduced into the index.html of the root directory by using the domestic bootcdn.

Add externals to webpack settings, ignoring libraries that don't need to be packaged.

externals: {  
  'vue': 'Vue',  
  'vue-router': 'VueRouter',  
  'vuex': 'Vuex',  
  'axios': 'axios'  
}  

Imported using cdn in index.html.

<script src="//cdn.bootcss.com/vue/2.2.5/vue.min.js"></script>  
<script src="//cdn.bootcss.com/vue-router/2.3.0/vue-router.min.js"></script>
<script src="//cdn.bootcss.com/vuex/2.2.1/vuex.min.js"></script>  
<script src="//cdn.bootcss.com/axios/0.15.3/axios.min.js"></script> 

Put the JS file at the end of the body

By default, in the index.html after the build, the introduction of js is in the header. 
Use the html-webpack-plugin plugin to change the value of inject to body. You can import js at the end of the body.

var HtmlWebpackPlugin = require('html-webpack-plugin');
new HtmlWebpackPlugin({
      inject: 'body',
})

Minify the code and remove the console

Use the UglifyJsPlugin plugin to minify the code and remove the console.

new webpack.optimize.UglifyJsPlugin({
  compress: {
    warnings: false,
    drop_console: true,
    pure_funcs: ['console.log']
  },
  sourceMap: false
})

For the time being, only these optimization methods have been found.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325130380&siteId=291194637