使用Webpack的多个页面的一个捆绑包

One bundle for several pages with Webpack

本文关键字:一个 Webpack 使用      更新时间:2023-09-26

我有几个页面,希望将所有脚本编译成一个包。

我知道每个页面可能有几个条目,但它会为不同的页面生成几个捆绑包。

为什么一个捆绑包对我来说如此重要:

  • 当结果是一个bundle而不是几个bundle(比如bundle-1.0.1.js)时,构建的版本控制更方便
  • 它可以缓存一次并在所有页面中使用

类似这样的东西:

page1.html
...
<script src="bundle.js" entry-module="module-for-page1"></script>
...
page2.html 
...
<script src="bundle.js" entry-module="module-for-page2"></script>
...

可能的解决方法的主要思想:

您可以在构建时将特殊的引导模块设置为入口点。在运行时,该模块从脚本标记属性中提取启动模块的名称,并有条件地要求它


webpack.config.js:

module.exports = {
   ...
   entry: "./webpack-entry-module.js",
   ...
}

webpack-entry-module.js:

var entryModule = document.querySelector('script').getAttribute('webpack-entry-module');
switch(entryModule) {
case 'module1.js': require('./module1.js'); break;
case 'module2.js': require('./module2.js'); break;
}

现在您可以参考html:中的模块

page1.html:
<script src="bundle.js" webpack-entry-module="module1.js"></script>
page2.html:
<script src="bundle.js" webpack-entry-module="module2.js"></script>



完整的示例如下:
https://github.com/artin-phares/webpack-entry-module

相关文章: