我有一个简单的示例应用程序,其结构如下:
/dist
index.html
app.bundle.js
moduleA.bundle.js
moduleB.bundle.js
vendors~app~moduleA~moduleB.bundle.js
[...sourcemaps]
/node_modules
[...]
/src
index.js
moduleA.js
moduleB.js
package.json
webpack.config.js
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Dependency Pulls</title>
</head>
<body>
<script type="text/javascript" src="app.bundle.js"></script>
</body>
</html>
src/index.js
import _ from 'Lodash';
import printA from './moduleA.js';
import printB from './moduleB.js';
function component() {
var element = document.createElement('div');
var btn = document.createElement('button');
element.innerHTML = _.join(['Hello', 'webpack', '4'], ' ');
btn.innerHTML = 'printA. Click me and check the console.';
btn.onclick = printA;
element.appendChild(btn);
btn = document.createelement('button');
btn.innerHTML = 'printB. Click me and check the console.';
btn.onclick = printB;
element.appendChild(btn);
return element;
}
document.body.appendChild(component());
src/moduleA.js
import printB from './moduleB.js';
export default function printA() {
console.log('AAA I get called from moduleA.js!');
}
src/moduleB.js
import _ from 'Lodash';
export default function printB() {
console.log('BBB I get called from moduleB.js!');
}
/webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
app: './src/index.js',
moduleA: './src/moduleA.js',
moduleB: './src/moduleB.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
optimization: {
splitChunks: {
chunks: 'all'
}
}
}
当我拉取 app.bundle.js 时,我希望 vendor 包也能自动拉取,因为它是 app.js 的依赖项。目前,这并没有发生—— vendor 包没有被加载。我什至没有在网络选项卡中看到任何尝试。
我如何告诉 webpack 自动加载包的依赖项?
最佳答案
Webpack 捆绑/依赖管理并不完全以这种方式工作。您需要手动添加一个 <script>
标记到每个包(条目)的 html。
但是,您可能需要考虑使用:
html-webpack-plugin:
https://www.npmjs.com/package/html-webpack-plugin
https://webpack.js.org/plugins/html-webpack-plugin
这会自动将包引用注入(inject)到您的 html。
html-webpack-template:
https://github.com/jaketrent/html-webpack-template
也可能有助于额外的定制/功能。
关于javascript - 通过 Webpack 动态加载/导入拆分的 vendor block /包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390841/