我正在使用webpack将新的(React)代码部分更新到现有的Web应用程序中,并将所有东西绑定在一起以供生产使用。由于现有的HTML页面(实际上是XML转换为HTML)已经存在,因此我无法使用由HtmlWebpackPlugin
生成的index.html
。
我的目标是使webpack生成一个小的runtime.bundle.js
,它将动态加载其他生成的块(main.[contenthash]
和vendor.[contenthash]
),而不是将这些条目作为script
标签添加到index.html
。这样runtime.bundle.js
可以设置为nocache
,而大型的其他块可以由浏览器缓存并在代码更改时正确获取。
以下是生成的index.html
的body块的示例,请注意注释:
<html>
<head>...</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="runtime.bundle.js"></script>
<!-- I want these two files below not injected as script tags,
but loaded from the runtime.bundle.js file above -->
<script type="text/javascript" src="vendors.31b8acd750477817012d.js"></script>
<script type="text/javascript" src="main.1e4a456d496cdd2e1771.js"></script>
</body>
</html>
运行时文件已经加载了通过以下代码动态从JS导入的不同块:
const App = React.lazy(() => import(/* webpackChunkName: "modulex" */ './App'));
这将在
runtime.bundle.js
中的某处创建以下片段。 a = document.createElement('script');
(a.charset = 'utf-8'),
(a.timeout = 120),
i.nc && a.setAttribute('nonce', i.nc),
(a.src = (function(e) {
return (
i.p +
'' +
({ 1: 'modulex' }[e] || e) +
'.' +
{ 1: '0e0c4000d075e81c1e5b' }[e] +
'.js'
);
那么,vendors
和main
代码块可以实现相同的效果吗?
我能想到的唯一另一个替代方案是使用WebpackManifestPlugin
生成manifest.json
并使用它将代码块注入到已经存在的HTML文件中。
manifest.json
)。这个脚本可以作为npm脚本调用。如果你需要的话,我可以分享给你... - Sjiep