1.说明

官方文档
之前按需加载说过,自己写的代码可以拆分。但是node_modules的代码还是会打包在一个js中,这样的话还是会因为js文件太大。

2.案例

2.1.index.html

src\index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <div>Hello</div>
  9. </body>
  10. </html>

2.2.index.js

src\js\index.js

import $ from 'jQuery'

console.log($)

2.3.webpack.dll.js

webpack.dll.js

const { resolve } = require('path')
const webpack = require('webpack')

// webpack --config webpack.dll.js
module.exports = {
    mode: "production",
    // 入口文件
    entry: {
        // 参考:https://webpack.docschina.org/configuration/externals/#externals
        // key:要生成的文件名,即后面的[name]
        // value数组:即要打包的依赖,就是import的要引用的后面那个字符串
        //   如果项目中引入的是 `import $ from 'jQuery'` 就填 "jQuery"
        //   如果项目中引入的是 `import $ from 'jquery'` 就填 "jquery"
        //   这里使用"jQuery"是因为,jquery的package.json中title为"jQuery",name为"jquery",所以应该哪个都行
        //   但是,这也是jQuery库的不好,要是项目中两种都用了就麻烦了
        jquery: ["jQuery"],
        // react: ["react", "react-dom"]
    },
    output: {
        filename: "[name].js",
        path: resolve(__dirname, "dll"),
        library: "[name]_[fullhash]", // 打包后的文件向外输出的对象是什么,加上hash可以避免万一重复引用后,变量[name]冲突,也可以是"[name]_[hash]"
    },
    plugins: [
        new webpack.DllPlugin({
            context: __dirname,
            name: '[name]_[fullhash]', // 映射库的暴露内容名称,同上library
            path: resolve(__dirname, 'dll/[name].manifest.json'), // 输出的文件路径
        })
    ],
}

2.4.编译dll

webpack --config webpack.dll.js

2.5.安装资源添加插件

npm i add-asset-html-webpack-plugin -D

2.5.webpack.config.js

webpack.config.js

const { resolve } = require('path')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require('webpack')
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin')

module.exports = {
    mode: 'production',
    entry: './src/js/index.js',
    output: {
        filename: 'js/[name].[contenthash:10].js',
        path: resolve(__dirname, 'build')
    },
    plugins: [
        new HtmlWebpackPlugin({
            // 模板位置
            template: './src/index.html'
        }),
        // 告诉webpack那些库不用打包,并且使用时的名称也要修改
        new webpack.DllReferencePlugin({
            manifest: resolve(__dirname, 'dll/jquery.manifest.json'),
        }),
        // 将对应的js文件输出到output的path中,然后将改js文件添加到html中(所以此时的dll文件夹就多余了,记得添加到.gitignore)
        new AddAssetHtmlWebpackPlugin({
            filepath: resolve(__dirname, 'dll/jquery.js'),
        })
    ],
}