1. 程式人生 > >vue + webpack [email protected]打包注意事項總結(

vue + webpack [email protected]打包注意事項總結(

以下是用[email protected]構建的後臺管理系統中總結出來的打包注意事項

1,執行已有釋出環境打包命令 npm  run  build 以後,的dist資料夾放到本地部署的tomcat中執行,找不到檔案

      原因是,官方配置檔案 config/index.js中配置的 ‘assetsPublicPath‘屬性(即打包時,output的檔案路徑),將build中的assetsPublicPath改成‘./’;

     注意,dev中的assetsPublicPath不要改,否則 npm  run  dev會報錯

2,vue-cli預設開啟eslint檢查語法,比較嚴格

     關閉方法:1》 config/index.js   dev物件中,把useEslint的值改為false;

                          2》檔案頭部加一個 /*eslint-disable*/

*******************************************************************分割線***********************************************************************

打包優化

3, 打包速度優化

預設production環境是開啟sourceMap的,打包速度會比較慢,可以在config/index.js 的build物件中,把productionSourceMap屬性改為false,這樣打包出來的檔案中不會有map檔案,打包速度會提升

4,在build/webpack.base.config.js裡配置resolve.modules屬性,配置模組庫(即 node_modules)所在的位置,加快打包速度

module.exports = {
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    modules: [
      resolve('src'),
      resolve('node_modules')
    ],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },

5,loader中配置include和exclude,減少不必要的遍歷

include 包括路徑,

exclude,排除路徑

{
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')],
        exclude: /node_modules/
},

6,預設使用uglifyjs-webpack-plugin來壓縮檔案,但是是單執行緒壓縮,速度很慢,可以改用 webpack-parallel-uglify-plugin 外掛,它可以並行執行 UglifyJS 外掛,從而更加充分、合理的使用 CPU 資源,從而大大減少構建時間

1》npm i webpack-parallel-uglify-plugin -save-dev

2》build/webpack.prod.conf.js 檔案

//預設配置
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),

//改成如下

const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');

new ParallelUglifyPlugin({
      cacheDir: '.cache/',
      uglifyJS:{
        output: {
          comments: false
        },
        compress: {
          warnings: false
        }
      }
    }),

7,用happypack加速程式碼構建

執行在 Node.js 之上的 Webpack 是單執行緒模型的,而 HappyPack 的處理思路是:將原有的 webpack 對 loader 的執行過程,從單一程序的形式擴充套件多程序模式,從而加速程式碼構建

1》npm i happypack

2》 build/webpack.base.conf.js中,修改為

const HappyPack = require('happypack');
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        //把對.js 的檔案處理交給id為happyBabel 的HappyPack 的例項執行
        loader: 'happypack/loader?id=happyBabel',
        include: [resolve('src')],
        //排除node_modules 目錄下的檔案
        exclude: /node_modules/
      },
    ]
  },
  plugins: [
    new HappyPack({
        //用id來標識 happypack處理那裡類檔案
      id: 'happyBabel',
      //如何處理  用法和loader 的配置一樣
      loaders: [{
        loader: 'babel-loader?cacheDirectory=true',
      }],
      //共享程序池
      threadPool: happyThreadPool,
      //允許 HappyPack 輸出日誌
      verbose: true,
    })
  ]
}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

8,打包後文件大小

可以把一些不經常變化的檔案在index.html檔案中用script標籤引入,而不是在main.js中用import引入(前者不會被打包到app或者vendor檔案中,這樣這幾個檔案大小不會太大),引入後,需要在build/webpack.base.config.js中加入以下配置,告知webpack這些檔案不需要打包,例如 axios、element-ui,echarts、g2等外掛

externals:{

    'axios': 'axios',

    'Vue': 'Vue',
    'element-ui': 'ELEMENT',

    'G2':'G2',

    'DataSet': 'DataSet'

  }

9,引入UI框架

為防止引入UI框架後,打包檔案過大,可採取兩種方法(以element-ui為例):

1》按需引入,按照官網文件操作即可

import { Button, Select } from 'element-ui';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
Vue.prototype.$ELEMENT = { size: 'small', zIndex: 3000 };
/* 或寫為
 * Vue.use(Button)
 * Vue.use(Select)
 */

注意:按需引入需要在babel裡設定plugins,新增component項  同時需要安裝npm install babel-plugin-component -save-dev

{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

2》在index.html中用script標籤引入

詳細步驟,1)index.html引入index.css 和 index.js 檔案

                     2)main.js中去掉按需引入或者全部引入的element-ui語句

                     3) build/webpack.base.config.js中配置externals屬性,新增‘element-ui’: ‘ELEMENT’,操作類似方法4

                     4)main.js中加 Vue.use(ELEMENT,{size: 'small', zIndex: 1000})

10,抽離出css等樣式檔案,

安裝 npm install extract-text-webpack-plugin -save-dev

在module裡面新增loader,同時在plugins中新增以下程式碼,在一個環境中,兩者必須同時配置,否者會報錯

{
				test: /\.(scss|sass)$/,
				use: ExtractTextPlugin.extract({
				  use: ['css-loader', 'sass-loader'],
				  fallback: 'style-loader'
				})
			  // loader: 'style-loader!css-loader!sass-loader'
			},
new ExtractTextPlugin({
		  filename: utils.assetsPath('css/[name].[contenthash].css'),
		  
		  allChunks: true,
		}),

11,打包壓縮檔案 

該配置需要伺服器同步支援讀取gzip格式檔案

前端配置如下:

1》config/index.js 中 productionGzip: true, 如果是false,則改為true

2》npm install --save-dev compression-webpack-plugin

12,路由懶載入

當頁面過多時,需要在路由配置檔案中,配置成路由懶載入

{
    path:'',
    name:'',
    component: resolve => require(['@/views/partner/PartnerListView.vue'],resolve)}
}

或者

{
    path: '',
    name:'',
    component: resolve => {
        require.ensure(['./home.vue'], () => {
            resolve(require('./home.vue'))
        })
    }
}