优化项目

294 阅读1分钟

js文件按需加载

如果没有这个设置,项目首屏加载时会加载整个网站所有的JS文件,所以将JS文件拆开,点击某个页面时再加载该页面的JS是一个很好的优化方法。 这里用到的就是vue的组件懒加载。在router.js中,不要使用import的方法引入组件,使用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')))

html-webpack-plugin 将JS文件放在body的最后

默认情况下,build后的index.html中,js的引入实在是在head中,使用html-webpack-plugin插件,将inject的值改为body。就可以将js引入放到body最后。

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

externals 使用cdn

比如项目中的vuex,vue-router等插件,使用国内的bootcdn,直接引入到index.html中,在webpack中添加externals,忽略不需要打包的库

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  externals:{
    'vue':'Vue',
    'vue-router':'VueRouter',
    'vuex':'Vuex'
  },

Webpack Bundle Analyzer

我们可以使用webpack可视化插件Webpack Bundle Analyzer 查看工程js文件大小,然后有目的的解决过大的js文件。 安装

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

在webpack中设置如下,然后npm run dev的时候会默认在浏览器上打开

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = { plugins: [ new BundleAnalyzerPlugin() ] }

使用UglifyJsPlugin插件来压缩代码和移除console

new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false,
          drop_console:true,
          pure_funcs:['console.log']
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),