关于optimization.runtimeChunk: ‘single‘的理解

optimization.runtimeChunk: ‘single’ 一直很难理解,直到我看到了webpack的官方文档中说到的otherwise we could get into trouble described (下面称文章),下面我们就用两个例子把这个trouble复现一下。

Bug重现

文章中说,当两个模块从同一个模块(下面叫公用模块)中import后,公用模块的值,在同一个页面中(同一个runtime中),应该是多少?在文章中component-1和component-2都累加了1,因此输出应该是“1 2”,那么实验如下:

目录结构如下,其中component-1.js,component-2.js和obj.js的代码都是参考文章中,index.js可以忽略

关于optimization.runtimeChunk: ‘single‘的理解_第1张图片

webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    comp1: './src/component-1.js',//参考文章中的代码 
    comp2: './src/component-2.js',//参考文章中的代码
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

index.html

DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Developmenttitle>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script defer src="comp1.bundle.js">script>
    <script defer src="comp2.bundle.js">script>
  head>
  <body>
  body>
html>

解决方法

运行后你会发现,两次输出的都是1。这时候optimization.runtimeChunk: 'single’就有用了,按照官网手册的方法,你会发现,出现了一个runtime.bundle.js,这个玩意再在index.html中引用,结果就对了。

奇怪的地方

按照官网的方法,把obj.js独立成一个entry,component-1.js和component-2.js都dependOn,也不会出现这个问题。官网这个表述感觉确实很难理解,不过从另外一个角度来看,这个参数可能也没那么重要吧。

你可能感兴趣的:(JS,webpack,javascript)