Webpack DLL 设置教程

道理

DLL文件又称为动态链接库文件,它一般作为应用顺序可实行代码的一部分,供应用顺序在运转时举行挪用。

在Webpack中,内置的DllPlugin与DllReferencePlugin插件能够经由过程运用DLL来大幅进步构建机能,以下是DLL机制流程图:
《Webpack DLL 设置教程》

初始化项目

为了便于试验,我们经由过程运用create-react-app建立项目并eject出webpack设置:

npx create-react-app react-dll-demo
cd react-dll-demo && npm run eject

因为默许设置隐蔽了编译信息,翻开webpackDevServer.config.js,将quiet: true改成false,再启动一下项目,找出我们须要的信息:

Version: webpack 4.28.3
Time: 6985ms
Built at: 2019-02-21 10:46:42
                         Asset       Size        Chunks             Chunk Names
           asset-manifest.json  232 bytes                [emitted]
                    index.html   1.65 KiB                [emitted]
          static/js/0.chunk.js   4.21 MiB             0  [emitted]
           static/js/bundle.js   30.9 KiB  runtime~main  [emitted]  runtime~main
       static/js/main.chunk.js   47.4 KiB          main  [emitted]  main
static/media/logo.5d5d9eef.svg   2.61 KiB                [emitted]

DLLPlugin

起首在package.json的scripts字段增加一条剧本:

{
  "build:dll": "webpack --config config/webpack.dll.config.js --mode production"
}

然后建立设置文件:

// config/webpack.dll.config.js

const webpack = require('webpack');
const path = require('path');

module.exports = {
  entry: {
    react: ['react', 'react-dom']
  },
  output: {
    filename: '[name].dll.js',
    path: path.join(__dirname, '../public/dll'),
    libraryTarget: 'var',
    library: '_dll_[name]_[hash]'
  },
  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, '../public/dll', '[name].manifest.json'),
      name: '_dll_[name]_[hash]'
    })
  ]
};

实行npm run build:dll,CLI应该会自动提醒你装置webpack-cli,运转完成后能够看到以下文件:

public/dll
├── react.dll.js
└── react.manifest.json

DLLReferencePlugin

翻开config/webpack.config.js,在根对象plugins字段中写入该插件:

{
  plugins: [
    // ...
    new webpack.DllReferencePlugin({
        manifest: require(path.join(
        __dirname,
        '../public/dll/react.manifest.json'
        ))
    }),
  ]
}

末了一个步骤,在index.html我们先手动引入dll依靠:

    ...
    <div id="root"></div>
    <script src="/dll/react.dll.js"></script>
    ...

此时从新运转顺序,守候项目一般运转,再检查一下编译信息:

Version: webpack 4.28.3
Time: 4883ms
Built at: 2019-02-21 11:19:11
                         Asset       Size        Chunks             Chunk Names
           asset-manifest.json  232 bytes                [emitted]
                    index.html   1.69 KiB                [emitted]
          static/js/0.chunk.js   1.82 MiB             0  [emitted]
           static/js/bundle.js   30.9 KiB  runtime~main  [emitted]  runtime~main
       static/js/main.chunk.js   52.1 KiB          main  [emitted]  main
static/media/logo.5d5d9eef.svg   2.61 KiB                [emitted]

很显然的看到,在development形式下,构建时候降低了2s,打包大小降低了2.4M,置信将DLL运用到项目工程中,你能收获到更多的欣喜。

优化

以上顺序只是为了疾速入手与demo搭建,须要优化的处所另有许多,在此简朴的枚举几点,供人人参考。

自动注入编译文件到HTML

经由过程装置html-webpack-include-assets-plugin插件,能够自动将响应文件注入到index.html中,就能够防止手动举行更改了:

// config/webpack.config.js
const HtmlIncludeAssetsPlugin = require('html-webpack-include-assets-plugin');
// ...
{
  plugins: [
    new HtmlIncludeAssetsPlugin({
      assets: ['dll/react.dll.js'],
      append: false // 在其他资本前增加
    }),
  ]
}

DLL的缓存题目与自动加载

我们一般不会对html文件做缓存,每次发版本时采纳增量宣布,只需html的依靠文件名变了,则会从新去剖析静态资本列表。除此之外,还须要供应一个函数,自动去加载文件夹内的多进口dll文件,以下为中心代码:

config/dllHelper.js:

// config/dllHelper.js
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const dllConfig = require('./webpack.dll.config');

// 依据entry天生DllReferencePlugin列表
function genDllReferences() {
  return Object.keys(dllConfig.entry).map(
    name =>
      new webpack.DllReferencePlugin({
        manifest: require(path.join(
          __dirname,
          '../public/dll',
          `${name}.manifest.json`
        ))
      })
  );
}

// 天生dll文件的静态资本途径
function loadDllAssets() {
  return fs
    .readdirSync(path.resolve(__dirname, '../public/dll'))
    .filter(filename => filename.match(/.dll.js$/))
    .map(filename => `dll/${filename}`);
}

module.exports = {
  loadDllAssets,
  genDllReferences
};

config/webpack.dll.config.js:

// 
{
  ...
  output: {
    filename: '[name].[hash:8].dll.js'
  }
}

config/webpack.config.js:

const dllHelper = require('./dllHelper');
...
{
  plugins: [
    ...dllHelper.genDllReferences(),
    new HtmlIncludeAssetsPlugin({
      assets: dllHelper.loadDllAssets(), 
      append: false
    })
  ]
}

构建前清空文件夹

若DLLPlugiun的entry发生变化,则dll内的文件可能会越来越多,因而我们须要在构建dll前清空文件夹,在这里引荐这两个package:

  • npm-run-all,在scripts可串行或并行实行script
  • rimraf,nodejs删除文件利器

起首装置响应依靠:yarn add -D rimraf npm-run-all,然后修正package.json:

scripts: {
  "make:dll": "npm-run-all clear:dll build:dll",
  "build:dll": "webpack --config config/webpack.dll.config.js --mode production",
  "clear:dll": "rimraf public/dll",
}

以后在更改DLL时,一定要记得实行:npm run make:dll

其他

Demo堆栈地点:GitHub – vv13/react-dll-demo

    原文作者:vv13
    原文地址: https://segmentfault.com/a/1190000018239367
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞