Webpack 4 - 创建供应商块

时间:2018-02-26 10:02:22

标签: node.js webpack code-splitting webpack-4

在webpack 3配置中,我将使用下面的代码创建单独的vendor.js块:

entry: {
    client: ['./client.js'],
    vendor: ['babel-polyfill', 'react', 'react-dom', 'redux'],
},

output: {
  filename: '[name].[chunkhash].bundle.js',
  path: '../dist',
  chunkFilename: '[name].[chunkhash].bundle.js',
  publicPath: '/',
},

plugins: [
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'runtime',
    }),
],

通过所有更改,我不知道如何使用Webpack 4.我知道CommonChunksPlugin已被删除,因此有一种不同的方法可以实现。我还阅读了this tutorial,但我仍然不确定是否提取运行时块并正确定义output属性。

修改 不幸的是,我在这里遇到了最受欢迎的答案。查看my answer

7 个答案:

答案 0 :(得分:19)

您可以从entry属性中删除vendor并设置优化属性,如此...

entry: {
 client: './client.js'
},

output: {
 path: path.join(__dirname, '../dist'),
 filename: '[name].chunkhash.bundle.js',
 chunkFilename: '[name].chunkhash.bundle.js',
 publicPath: '/',
},

optimization: {
  splitChunks: {
   cacheGroups: {
    vendor: {
     test: /node_modules/,
     chunks: 'initial',
     name: 'vendor',
     enforce: true
    },
   }
  } 
 }

检查此来源webpack examples

答案 1 :(得分:12)

要分离供应商运行时,您需要使用optimization选项。

可能的Webpack 4配置:

// mode: 'development' | 'production' | 'none'

entry: {
    client: ['./client.js'],
    vendor: ['babel-polyfill', 'react', 'react-dom', 'redux'],
},

output: {
    filename: '[name].[chunkhash].bundle.js',
    path: '../dist',
    chunkFilename: '[name].[chunkhash].bundle.js',
    publicPath: '/',
},

optimization: {
    runtimeChunk: 'single',
    splitChunks: {
        cacheGroups: {
            vendors: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendors',
                enforce: true,
                chunks: 'all'
            }
        }
    }
}

有关W4的更多信息,请参阅此Webpack-Demo

此外,您可以将optimization.splitChunks.chunks属性更改为"all"。阅读更多here

  

注意:您可以通过optimization.splitChunks对其进行配置。这些示例说明了一些关于块的内容,默认情况下它只适用于异步块,但对于optimization.splitChunks.chunks: "all",初始块也是如此。

答案 2 :(得分:6)

过了一段时间我发现了这个配置:

@babel/polyfill

无法以某种方式加载导致浏览器不兼容错误的@babel/polyfill ...所以最近我查了updated webpack documentation并找到a way来创建正确的供应商块加载const moduleList = ["@babel/polyfill", "react", "react-dom"]; ... entry: { client: ["@babel/polyfill", "../src/client.js"] } optimization: { runtimeChunk: "single", splitChunks: { cacheGroups: { vendor: { test: new RegExp( `[\\/]node_modules[\\/](${moduleList.join("|")})[\\/]` ), chunks: "initial", name: "vendors", enforce: true } } } }

splitChunks.cacheGroups.vendor.test

请注意,我创建了一个条目,其中包含所有代码,然后我指定public class PageRankReader { public PageRankReader(String filename) { try { readPageRanks(filename); }catch (FileNotFoundException e) { System.err.println("File not found"); } } public static void main(String[] args) { if( args.length != 0) { System.err.println("Please provide name of the pageranks file"); } new PageRankReader(args[0]); } } 哪些模块应该是拆分为供应商块。

尽管如此,我不确定这是100%正确还是可以改进,因为这实际上是最混乱的事情之一。但是,这似乎与文档最接近,当我用webpack-bundle-analyzer检查它们时,似乎产生了正确的块(只更新了已更改的块,其余部分在构建中保持不变)并修复了< EM>填充工具

答案 3 :(得分:6)

为了减小供应商js包的大小。我们可以将节点模块软件包拆分为不同的捆绑文件。我引用此blog来拆分由webpack生成的庞大的供应商文件。我最初使用的链接的要点:

optimization: {
   runtimeChunk: 'single',
   splitChunks: {
    chunks: 'all',
    maxInitialRequests: Infinity,
    minSize: 0,
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name(module) {
        // get the name. E.g. node_modules/packageName/not/this/part.js
        // or node_modules/packageName
        const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

      // npm package names are URL-safe, but some servers don't like @ symbols
      return `npm.${packageName.replace('@', '')}`;
      },
    },
  },
 },
}

如果要将多个包装和大块包装在一起,然后分成不同的捆,请参考以下要点。

optimization: {
runtimeChunk: 'single',
  splitChunks: {
    chunks: 'all',
    maxInitialRequests: Infinity,
    minSize: 0,
    cacheGroups: {
      reactVendor: {
        test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
        name: "reactvendor"
      },
      utilityVendor: {
        test: /[\\/]node_modules[\\/](lodash|moment|moment-timezone)[\\/]/,
        name: "utilityVendor"
      },
      bootstrapVendor: {
        test: /[\\/]node_modules[\\/](react-bootstrap)[\\/]/,
        name: "bootstrapVendor"
      },
      vendor: {
         test: /[\\/]node_modules[\\/](!react-bootstrap)(!lodash)(!moment)(!moment-timezone)[\\/]/,
      name: "vendor"
    },
    },
  },
}

答案 4 :(得分:5)

我想如果你这样做:

optimization: {
    splitChunks: {
        chunks: 'all',
    },
    runtimeChunk: true,
}

它会为您创建一个vendors~runtime~块。 Sokra said splitChunks的默认值为:

splitChunks: {
    chunks: "async",
    minSize: 30000,
    minChunks: 1,
    maxAsyncRequests: 5,
    maxInitialRequests: 3,
    name: true,
    cacheGroups: {
        default: {
            minChunks: 2,
            priority: -20
            reuseExistingChunk: true,
        },
        vendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10
        }
    }
}

其中已包含vendorsdefault捆绑包。在测试中,我还没有看到default捆绑出现。

我不知道包含这些文件的预期工作流程是什么,但我在PHP中编写了这个辅助函数:

public static function webpack_asset($chunkName, $extensions=null, $media=false) {
    static $stats;
    if($stats === null) {
        $stats = WxJson::loadFile(WX::$path.'/webpack.stats.json');
    }
    $paths = WXU::array_get($stats,['assetsByChunkName',$chunkName],false);
    if($paths === false) {
        throw new \Exception("webpack asset not found: $chunkName");
    }
    foreach($stats['assetsByChunkName'] as $cn => $files) {
        if(self::EndsWith($cn, '~' . $chunkName)) {
            // prepend additional supporting chunks
            $paths = array_merge($files, $paths);
        }
    }
    $html = [];
    foreach((array)$paths as $p) {
        $ext = WXU::GetFileExt($p);
        if($extensions) {
            if(is_array($extensions)) {
                if(!in_array($ext,$extensions)) {
                    continue;
                }
            } elseif(is_string($extensions)) {
                if($ext !== $extensions) {
                    continue;
                }
            } else {
                throw new \Exception("Unexpected type for \$extensions: ".WXU::get_type($extensions));
            }
        }
        switch($ext) {
            case 'js':
                $html[] = WXU::html_tag('script',['src'=>$stats['publicPath'].$p,'charset'=>'utf-8'],'');
                break;
            case 'css':
                $html[] = WXU::html_tag('link',['href'=>$stats['publicPath'].$p,'rel'=>'stylesheet','type'=>'text/css','media'=>$media],null); // "charset=utf-8" doesn't work in IE8
                break;
        }
    }
    return implode(PHP_EOL, $html);
}

哪个适用于我的资产插件(针对WP4更新):

{
    apply: function(compiler) {
        //let compilerOpts = this._compiler.options;
        compiler.plugin('done', function(stats, done) {
            let assets = {};
            stats.compilation.namedChunks.forEach((chunk, name) => {
                assets[name] = chunk.files;
            });

            fs.writeFile('webpack.stats.json', JSON.stringify({
                assetsByChunkName: assets,
                publicPath: stats.compilation.outputOptions.publicPath
            }), done);
        });
    }
},

所有这些都吐出了类似的东西:

<script src="/assets/runtime~main.a23dfea309e23d13bfcb.js" charset="utf-8"></script>
<link href="/assets/chunk.81da97be08338e4f2807.css" rel="stylesheet" type="text/css"/>
<script src="/assets/chunk.81da97be08338e4f2807.js" charset="utf-8"></script>
<link href="/assets/chunk.b0b8758057b023f28d41.css" rel="stylesheet" type="text/css"/>
<script src="/assets/chunk.b0b8758057b023f28d41.js" charset="utf-8"></script>
<link href="/assets/chunk.00ae08b2c535eb95bb2e.css" rel="stylesheet" type="text/css" media="print"/>

现在当我修改我的一个自定义JS文件时,只有其中一个JS块发生了变化。运行时和供应商包都不需要更新。

如果我添加一个新的JS文件并require它,运行时仍然没有更新。我认为因为新文件将被编译到主包中 - 它不需要在映射中,因为它不是动态导入的。如果我import()它导致代码分裂,那么然后运行时会更新。供应商捆绑似乎已经改变了 - 我不知道为什么。我认为应该避免这种情况。

我还没弄明白如何处理每个文件的哈希值。如果您修改与.css文件相同的.js文件,则其文件名将随[chunkhash]一起更改。

我更新了上面的资产插件。我认为您添加<script>代码的顺序可能很重要...这将保持订单AFAICT:

const fs = require('fs');

class EntryChunksPlugin {

    constructor(options) {
        this.filename = options.filename;
    }

    apply(compiler) {
        compiler.plugin('done', (stats, done) => {
            let assets = {};

            // do we need to use the chunkGraph instead to determine order??? https://gist.github.com/sokra/1522d586b8e5c0f5072d7565c2bee693#gistcomment-2381967
            for(let chunkGroup of stats.compilation.chunkGroups) {
                if(chunkGroup.name) {
                    let files = [];
                    for(let chunk of chunkGroup.chunks) {
                        files.push(...chunk.files);
                    }
                    assets[chunkGroup.name] = files;
                }
            }

            fs.writeFile(this.filename, JSON.stringify({
                assetsByChunkName: assets,
                publicPath: stats.compilation.outputOptions.publicPath
            }), done);
        });
    }
}

module.exports = EntryChunksPlugin;

答案 5 :(得分:2)

我发现了一种更短的方法:

optimization: {
  splitChunks: { name: 'vendor', chunks: 'all' }
}

splitChunks.name作为字符串给出时,documentation说:“指定字符串或总是返回相同字符串的函数会将所有通用模块和供应商合并为一个块。” 与splitChunks.chunks结合使用,它将提取所有依赖项。

答案 6 :(得分:0)

入口文件的顺序似乎也很重要。由于您在供应商之前拥有client.js,因此不会在主应用程序之前在供应商之间发生捆绑。

entry: {
 vendor: ['react', 'react-dom', 'react-router'],
 app: paths.appIndexJs
},

现在通过 SplitChunks 优化,您可以指定输出文件名,并将条目名称供应商引用为:

optimization: {
 splitChunks: {
  cacheGroups: {
    // match the entry point and spit out the file named here
    vendor: {
      chunks: 'initial',
      name: 'vendor',
      test: 'vendor',
      filename: 'vendor.js',
      enforce: true,
    },
  },
 },
},