webpack优化环境配置 - 28.dll

随着项目越来越大,项目里的依赖包也越来越多,所以打包和项目启动速度会变慢。
使用dll技术,对某些库(第三方库:jquery、react、vue...)进行单独打包
从而每次只需要打包真正的项目代码,提升了打包速度。
 

当你运行 webpack 时,默认查找 webpack.config.js 配置文件
  需求:需要运行 webpack.dll.js 文件
  --> webpack --config webpack.dll.js

 

1.文件结构

 

 

 

2.安装插件,将某个文件打包输出去,并在html中自动引入该资源。

$ npm i add-asset-html-webpack-plugin@3.1.3 -D

 

3.代码

manifest.json

{
  "name": "jquery_cceadeb3136485335e4c",
  "content": {
    "../node_modules/jquery/dist/jquery.js": {
      "id": 1,
      "buildMeta": {
        "providedExports": true
      }
    }
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h5>hello html</h5>
</body>
</html>

index.js

import $ from 'jquery'

console.log($)

webpack.dll.js

/*
  使用dll技术,对某些库(第三方库:jquery、react、vue...)进行单独打包
    当你运行 webpack 时,默认查找 webpack.config.js 配置文件
    需求:需要运行 webpack.dll.js 文件
      --> webpack --config webpack.dll.js
*/

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

module.exports = {
    entry: {
        // 最终打包生成的[name] --> jquery
        // ['jquery'] --> 要打包的库是jquery  (只要 jquery 不变,打包一次即可,不用重复打包)
        jquery: ['jquery'],
    },
    output: {
        filename: '[name].js',
        path: resolve(__dirname, 'dll'),
        library: '[name]_[hash]' // 打包的库里面向外暴露出去的内容叫什么名字
    },
    plugins: [
        // 打包生成一个 manifest.json --> 提供和jquery映射
        new webpack.DllPlugin({
            name: '[name]_[hash]', // 映射库的暴露的内容名称
            path: resolve(__dirname, 'dll/manifest.json') // 输出文件路径
        })
    ],
    mode: 'production'
};

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 = {
    entry: './src/index.js',
    output: {
        filename: "built.js",
        path: resolve(__dirname, 'build')
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
        // // 告诉 webpack 哪些库不参与打包,同时使用时的名称也得变~   (打包时忽略 jquery)
        new webpack.DllReferencePlugin({
            manifest: resolve(__dirname, 'dll/manifest.json')
        }),
        // // 将某个文件打包输出去,并在html中自动引入该资源   (将之前打包的 jquery 的包进入进来)
        new AddAssetHtmlWebpackPlugin({
            filepath: resolve(__dirname, 'dll/jquery.js')
        })
    ],
    mode: 'production'
}

 

4.打包

$ webpack

 

 end~

posted @ 2022-09-09 10:56  Evengod  阅读(25)  评论(0编辑  收藏  举报