Dll 前端 工程优化

一、为什么前端需要用到Dll?

1、提升编译速度,在webpack中默认使用commoncheckplugin来进行公共依赖的抽取

但是没有提升编译速度,在大型项目中编译时间很长。

2、生成的依赖文件和第三方的依赖关系,文件缓存。

 

二、使用Dll用到哪些插件,都有什么作用?

1、DllPlugin,用于打包出需要动态加载的第三方依赖,一般情况包含package.jsondependencies对象,

配置独立的打包文件,输出文件有两个: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文件,注意引入的文件路径。

posted @ 2020-01-08 16:00  kimoon  阅读(1088)  评论(0编辑  收藏  举报