使用 Webpack 将多个页面捆绑在一起
One bundle for several pages with Webpack
我有几个页面,想将所有脚本编译成一个包。
我知道每个页面可以有多个条目,但它会为不同的页面生成多个包。
为什么一个包对我来说如此重要:
- 当结果是一个包而不是几个包时,版本控制更方便(比如 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>
...
可能的解决方法的主要想法:
您将特殊的 bootstrap 模块设置为构建时的入口点。
当运行时,本模块从script-tag属性中提取启动模块名称,并有条件地要求它。
webpack.config.js:
module.exports = {
...
entry: "./webpack-entry-module.js",
...
}
webpack-入口-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
我有几个页面,想将所有脚本编译成一个包。
我知道每个页面可以有多个条目,但它会为不同的页面生成多个包。
为什么一个包对我来说如此重要:
- 当结果是一个包而不是几个包时,版本控制更方便(比如 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>
...
可能的解决方法的主要想法:
您将特殊的 bootstrap 模块设置为构建时的入口点。 当运行时,本模块从script-tag属性中提取启动模块名称,并有条件地要求它。
webpack.config.js:
module.exports = {
...
entry: "./webpack-entry-module.js",
...
}
webpack-入口-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