1. 程式人生 > >vue專案打包後文件過大怎麼辦,如何優化載入速度

vue專案打包後文件過大怎麼辦,如何優化載入速度

路由懶載入

const Home = () => import('./views/Home.vue');
const MyInfo = () => import('./views/MyInfo.vue');

在.babelrc中

"plugins": ["@babel/plugin-syntax-dynamic-import"]

分離公共程式碼

webpack 3.x

new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // any required modules inside node_modules are extracted to vendor
        // 翻譯註釋:所有被依賴的模組,如果它在node_modules目錄中,都會被抽離出來放進 vendor.js 中
        // 如果模組有一個路徑,而且在路徑中有 js 檔案,並且這個模組是屬於 node_modules 中的模組
        // 那這個模組就會被抽離出來,放進名為 vendor 的這個chunk
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: ['vendor']
    }),

webpack 4.x

optimization與output同級

 optimization: {
    runtimeChunk: {
      name: 'manifest'
    },
    splitChunks: {
      chunks: 'async',
      minChunks: 2,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      name: false,
      cacheGroups: {
        vendor: {
          name: 'vendor',
          // chunks 有三個可選值,”initial”, “async” 和 “all”. 分別對應優化時只選擇初始的chunks,所需要的chunks 還是所有chunk
          chunks: 'initial',
          priority: -10,
          reuseExistingChunk: false,
          test: /[\\/]node_modules[\\/]/
        }
      }
    }
  },

css懶載入

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

該外掛需要webpack 4.x

//sass
      {
        test: /\.(sc|sa|c)ss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ]
      },

plugins中:

new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css',
      chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',
    }),

CDN引入

  <script src="https://cdn.bootcss.com/vue/2.5.21/vue.min.js"></script>
  <script src="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.min.js"></script>
  <script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
  <script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
  <script src="https://unpkg.com/vant/lib/vant.min.js"></script>

webpack.base.conf.js中

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

externals與output同級。

刪掉專案中import的這幾個相關的,以及Vue.use()。eslint外掛報錯not defined的話,前面加個window,如window.VueRouter。

js壓縮、css壓縮

這個就不說了。

推薦使用webpack 4.x,在production模式下有Tree Shaking和Scope Hoisting。
如果還是過大,可以使用下面外掛:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
plugins: [
      new BundleAnalyzerPlugin()
  ]

它會生成一個分析圖,你的檔案裡包含了哪些檔案,打包後,它會自動在瀏覽器中開啟。