1、安装依赖(clean-webpack-plugin、add-asset-html-webpack-plugin、webpack-cli)

yarn add clean-webpack-plugin add-asset-html-webpack-plugin webpack-cli -D

2、项目根目录新建 webpack.dll.config.js,内容如下

const path = require('path')
const webpack = require('webpack')
const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin')


// dll文件抽取的目录
const dllPath = 'public/vendor'

module.exports = {
  entry: {
    // 需要提取的库文件
    vendor: ['react','qs','react-helmet','echarts','echarts-for-react','antd','ahooks','aws-sdk','react-dom','react-redux','redux','react-router-dom','react-router-config','react-router','redux-thunk','redux-devtools-extension','axios','less','less-loader','xlsx','crypto-js','dayjs']   //依赖根据自己的package.json来编写,这是我自己项目中的
  },
  output: {
    path: path.join(__dirname, dllPath),
    filename: '[name].dll.js',
    // 与 webpack.DllPlugin 中的名称一样
    library: '[name]_[hash]'
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DllPlugin({
      path: path.join(__dirname, dllPath, '[name]-manifest.json'),
      // 与 output.library的名称一样
      name: '[name]_[hash]',
      context: process.cwd(),
})
]
}

3、package.json 中 scripts 括号内,新增一行

"dll": "webpack  --progress --config ./webpack.dll.config.js",

4、在config-overrides.js 中配置(config-overrides可以在网上找教程)

const {
  override,
 
} = require("customize-cra");
const webpack = require("webpack");
const AddAssetHtmlPlugin = require("add-asset-html-webpack-plugin");
const path = require("path");
const addDll = () => (config) => {
  if (config.mode === "production") {
    config.devtool = false; //去掉map文件
    config.plugins.push(
      new webpack.DllReferencePlugin({
        context: process.cwd(),
        manifest: require("./public/vendor/vendor-manifest.json"),
      }),
      //dll 添加到生成的html文件中
      new AddAssetHtmlPlugin({
        // dll文件位置
        filepath: path.resolve(__dirname, "./public/vendor/*.js"),
        // dll 引用路径,不能用./,否则刷新会报错
        publicPath: "/vendor",
        // dll输出的目录
        outputPath: "./vendor",
      })
    );
  }

  return config;
};
module.exports = override(
addDll
)

  

 

posted on 2022-01-25 10:12  随心的博客  阅读(542)  评论(0编辑  收藏  举报