一、為什么前端需要用到Dll?
1、提升編譯速度,在webpack中默認使用commoncheckplugin來進行公共依賴的抽取
但是沒有提升編譯速度,在大型項目中編譯時間很長。
2、生成的依賴文件和第三方的依賴關系,文件緩存。
二、使用Dll用到哪些插件,都有什么作用?
1、DllPlugin,用於打包出需要動態加載的第三方依賴,一般情況包含package.json中dependencies對象,
配置獨立的打包文件,輸出文件有兩個:dll.manifest.json 包含第三庫在項目中的依賴加載關系、dll.libs.js 包含對所有第三方庫的抽離和壓縮
2、DllReferencePlugin,webpack配置文件中引入 manifest.json 文件
3、AddAssetHtmlPlugin,向打包輸出的index.html 中添加 dll.libs.js
三、生成第三方文件依賴關系和合並包文件
DllPlugin 生成這個dll庫,需要獨立的webpack命令打包輸出,基本的webpack配置如下:
const path = require('path') // 工程路徑 const webpack = require('webpack') // webpack工具 const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 代碼壓縮工具,事實證明使用了DllPlugin 也有必要壓縮 const env = require('../config/prod.env') const RootPath = path.resolve(__dirname, "../") const ScriptPath = path.resolve(RootPath, "./scripts") const pkg = require("./package.json"); let libs = Object.keys(pkg.dependencies || {}); if (exclude && exclude.length > 0) { libs = libs.filter(item => { return exclude.indexOf(item) == -1 }) } module.exports = { entry: { libs: libs }, output: { path: ScriptPath, filename: 'dll.[name].js', library: '[name]_library' }, plugins: [ new webpack.DefinePlugin({ 'process.env': env }), new UglifyJsPlugin({ uglifyOptions: { compress: {
unused: true, dead_code: true, pure_getters: true, warnings: false, screw_ie8: true, conditionals: true, comparisons: true, sequences: true, evaluate: true, join_vars: true, if_return: true
}
},
sourceMap: false,
parallel: true
}),
new webpack.DllPlugin({
path: path.resolve('.', '[name]-manifest.json'),
name: 'dll'
})
]
}
輸出的文件目錄:dll.libs.js 和 dll.manifest.json。
四、在開發環境中引入依賴關系和合並的包
DllReferencePlugin 實際在工程開發環境中,需要引入dll打包好的依賴關系包。引入方式如下:
在工程的webpack主入口的擴展插件中,添加以下配置
plugins: [ new webpack.DllReferencePlugin({ manifest: path.resolve(ScriptPath, './dll.manifest.json') }), new AddAssetHtmlPlugin({ filepath: path.resolve(ScriptPath, 'dll.libs.js'), outputPath: 'js', publicPath: "/js", includeSourcemap: false, hash: true, })
]
打包 dll 和 引入 json文件,注意引入的文件路徑。