webpack - 两个模块相互 import 的时候,执行会出现 TypeError
问题描述
2016-07-28 update
不好意思,我发现这不是 WebPack 造成的问题。一开始因为使用 TypeScript 直接编译成单个文件单独引用的时候没出现问题,打包后才出现的,所以误以为是 Webpack 的问题。但实际应该和引入文件的顺序有关。
(Sorry, I think it's not a problem comes from Webpack. It's a structure problem. Previously I compile sources by TypeScript compiler to separate JS files, and include then separately. There was no problem so I mistake consider that's a problem from webpack. )
由于历史问题,如果 import 的话,会带来非常大量的修改,那么是有办法在 webpack 打包的时候按照一定的依赖关系来进行呢?
(Since there are historical issues, we need much time to modify structure with import
, so is there a way to make order while bundling by webpack?)
为了描述这个问题,我写了个小 Demo,先上图,概览。
(I take a picture to show the overview of the question.)
代码如下 (Here is codes)
a.js
import B from "./b";
export class A {
test() {
console.log("hello webpack");
}
}
export default A;
b.js
import A from "./a";
export class B extends A {
}
export default B;
index.js
import T from "./a";
new T().test();
webpack.config.js
const webpack = require("webpack");
const path = require("path");
function resolve(...args) {
return path.resolve(__dirname, ...args);
}
const target = resolve("dist");
module.exports = {
entry: {
index: resolve("src/index.js")
},
output: {
path: target,
filename: "[name].js"
},
devtool: "source-map",
resolve: {
extensions: [".js"]
},
externals: {
jquery: "jQuery"
}
};
打包没问题,但是运行会报告 TypeError,大概是因为定义 B 的时候,其父类 A 还没定义……
(make bundle OK, but a TypeError is reported when running. Maybe because while defining B, its parent A is null)
请问,这个问题该如何解决?
(So, how to solve this problem?)
PS: 在 index.js 中使用 import T from "./b"
不会有问题。但因为这是为了描述问题专门写的 Demo,所以请忽略这一点。
(PS, change first line of index.js to import T from "./b"
, it runs fine. But Please ignore that way since I write the demo specially to describe problem.)
我通过为目录添加 index.js 解决了这个问题。
index.js 中按一定顺序引入目录(及子目录下)的所有模块,并导出。外部引用直接引用这个 index.js 即可。Webpack 打包的时候也能保证顺序
问题中,原来作为应用的 index.js 在这里改名为 app.js
index.js
export { B } from "./b";
export { A } from "./a";
这篇关于webpack - 两个模块相互 import 的时候,执行会出现 TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!