当我在单独的模块中多次使用System.import()
时,其中一个在第一次尝试时不起作用(Webpack的require函数返回modules[moduleId] is undefined
),但在第二次和后续尝试时它会正常加载。
文件夹结构
[webpack-test]
----[modules]
--------foo.js
--------bar.js
--------dateHelper.js
----[node_modules]
----0.app.dist.js
----0.charts.dist.js
----1.app.dist.js
----3.app.dist.js
----app.dist.js
----app.js
----charts.dist.js
----charts.js
----index.html
----package.json
----webpack.config.js
<小时/> index.html的
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="./app.dist.js"></script>
<script src="./charts.dist.js"></script>
</head>
<body>
</body>
</html>
<小时/> 的package.json
{
"name": "webpack-test",
"version": "1.0.0",
"devDependencies": {
"path": "^0.12.7",
"webpack": "^2.2.0-rc.3"
}
}
<小时/> webpack.config.js
var path = require('path');
module.exports = function () {
return [
// APP:
{
resolve: {
modules: [
path.resolve('./modules/')
]
},
entry: './app.js',
output: {
filename: 'app.dist.js',
}
},
// CHARTS:
{
resolve: {
modules: [
path.resolve('./modules/')
]
},
entry: './charts.js',
output: {
filename: 'charts.dist.js',
}
}
];
};
<小时/> app.js
export default (function () {
setInterval(function () {
System.import('foo').then(foo => { // breaks at first attempt
console.log('foo imported');
});
System.import('bar').then(bar => {
console.log('bar imported');
});
}, 3000);
})();
<小时/> foo.js
export default (function foo() {
console.log('foo');
})();
<小时/> bar.js
export default (function bar() {
console.log('bar');
})();
<小时/> dateHelper.js
export default (function dateHelper() {
console.log('dateHelper');
})();
<小时/> charts.js
export default (function charts() {
System.import('dateHelper').then(dateHelper => {
console.log('dateHelper imported');
})
})();
控制台输出:
0.charts.dist.js:8 dateHelper
charts.dist.js:152 dateHelper import
app.dist.js:48 Uncaught(in promise)TypeError:无法在__webpack_require__处读取未定义的属性'call'(app.dist.js:48)
modules [moduleId] .call(module.exports,module,module.exports,__ webpack_require __);
1.app.dist.js:8 bar
app.dist.js:156 bar导入
app.dist.js:153 foo导入
app.dist.js:156 bar导入
输出应为:
0.charts.dist.js:8 dateHelper
charts.dist.js:152 dateHelper import
0.app.dist.js:8 foo
app.dist.js:153 foo导入
1.app.dist.js:8 bar
app.dist.js:156 bar导入
app.dist.js:153 foo导入
app.dist.js:156 bar导入