wuye1200 / blog

alber blog
0 stars 0 forks source link

webpack 打包优化 #25

Open wuye1200 opened 5 years ago

wuye1200 commented 5 years ago
  1. DllPlugin DllReferencePlugin cnd静态文件
  2. 懒加载
  3. HappyPack
  4. CommonsChunkPlugin 提取公共文件
wuye1200 commented 5 years ago

vue-cli3 DllPlugin 实现预编译,提升构建速度

先安装

npm install webpack-cli --save-d 

独立出一套webpack配置webpack.dll.conf,用dllPlugin定义要打包的dll文件;这里我在根目录下新建webpack.dll.conf.js 内容如下

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: {
    vendor: [
      "vue-router/dist/vue-router.esm.js",
      "vuex/dist/vuex.esm.js",
      "axios"
    ]
  },
  output: {
    path: path.join(__dirname, "public/vendor"),
    filename: "[name].dll.js",
    library: "[name]_[hash]" // vendor.dll.js中暴露出的全局变量名
  },
  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, "public/vendor", "[name]-manifest.json"),
      name: "[name]_[hash]",
      context: process.cwd()
    })
  ]
};

注意一定要把生成的dll放到public中或者自己去配置 publicPath

package.json中定义运行webpack.dll.conf.js的命令

{
···
  "scripts": {
    "serve": "npm link typescript && vue-cli-service serve",
    "dll": "webpack -p --progress --config ./webpack.dll.conf.js",
···
  },
···
}

运行npm run dll命令生成dll

index.html中加载生成的dll文件

<script src="./vendor/vendor.dll.js"></script>

vue.config.js的配置文件中添加

const webpack = require("webpack");
module.exports = {
···
  configureWebpack: {
    plugins: [
      new webpack.DllReferencePlugin({
        context: process.cwd(),
        manifest: require("./public/vendor/vendor-manifest.json")
      })
    ]
  }
···
}