dll

Reads: 986 Edit

将依赖的库单独拆开来,打包成不通的chunk

在工程目录下新建 webpack.dll.js

//引用Node.js中的path模块,处理文件路径的小工具
const path = require("path");
const webpack = require("webpack")

/**
   使用dll技术,对某些库(jquery, vue, react ...)进行单独打包
   当运行 webpack是,默认查找 webpack.config.js配置文件
   需要运行 webpack.dll.js
   webpack --config webpack.dll.js
 */
// 导出一个webpack具有特殊属性配置的对象
module.exports = {
    entry:{
        jquery : ['jquery']
    },
    output: {
        //path是一个绝对路径,__dirname 是当前js的绝对路径
        path: path.join(__dirname , "./dll"),  
        filename : "[name].js" ,
        library : "[name]_[hash]"  // 打包的库想外暴露出去的内容叫什么名字
    },
    plugins:[
        new webpack.DllPlugin({
            name : "[name]_[hash]" , //映射库的暴露的内容名称
            path: path.join(__dirname , "./dll/manifest.json")
        }) 
           
    ],
    mode: "development" 
    
   
   
}

在命令行输出命令

webpack --config webpack.dll.js

130

会发现 dll库下有我们依赖的jquery库,

修改 index.js

import $ from 'jquery'

console.log($)

console.log("hello webpack")

修改index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>    
     
</body>
</html>

下载插件

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

修改 webpack.config.js

//引用Node.js中的path模块,处理文件路径的小工具
const path = require("path");
//引入插件
const HtmlwebpackPlugin = require("html-webpack-plugin")
const webpack = require("webpack")
const AddAssetHtmlWebpackPlugin = require("add-asset-html-webpack-plugin")

// 导出一个webpack具有特殊属性配置的对象
module.exports = {
    mode: "development" ,
    //多入口
    entry: "./src/js/index.js" ,
    //出口是对象
    output: {
        //path是一个绝对路径,__dirname 是当前js的绝对路径
        path: path.join(__dirname , "./dist/"), //打包的结果文件存储目录
        filename : "built.js"  //打包的结果文件名
    },
    //配置插件
    plugins: [
        new HtmlwebpackPlugin({
            //此插件作用是将 index.html打包到bundle.js所在目录中
            //同时会在 index.html中自动的在<script>引入 bundle.js
            template : "./src/index.html"
        }),
        // 告诉webpack那些库不参与打包,同时使用时的名称也得改
        new webpack.DllReferencePlugin({
            manifest:  path.join(__dirname , "./dll/manifest.json")
        }),
        // 将某个文件打包输出去,并在html文件中自动引入该资源
        new AddAssetHtmlWebpackPlugin({
            filepath : path.join(__dirname , "./dll/jquery.js")
        })
    ]
   
}

在运行 npm run build命令,会发现 dist目录下有我们打包依赖的jquery 并且index.html已经自动引入了。

22303

关于作者

王硕,网名信平,十多年软件开发经验,业余架构师,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。