我的目标是使用typescript 2.5.2和webpack 3.8.1使这个测试用例工作。这是我遇到的问题的简化。
简单的html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<script>
var baz = new Baz(); // alerts 'constructor'
alert(baz.createBar().getValue());
alert(baz.createFoo().getValue());
</script>
</body>
</html>
我有以下三个TS文件:
main.ts
import {Foo} from "./foo";
import {Bar} from "./bar";
export class Baz {
static bucket = {};
private name: string;
constructor(a: string) {
this.name = a;
alert('constructor');
}
static recordModule(indexCode: string, objectName: string) {
Baz.bucket[indexCode] = objectName;
console.log("Module " + objectName + " recorded with index " + indexCode);
alert(objectName);
}
public createFoo(): Foo{
return new Foo(1);
}
public createBar(): Bar{
return new Bar(2);
}
}
这个类只有一个构造函数,一个静态recordModule方法和两个create方法。
然后,我们有两个类似的类文件,也称为静态方法。
foo.ts
import {Baz} from "./main";
export class Foo {
private value: number;
constructor(val: number) {
this.value = val;
}
getValue(): number {
return this.value;
}
}
Baz.recordModule('F', 'Foo');
bar.ts
import {Baz} from "./main";
export class Bar {
private value: number;
constructor(val: number) {
this.value = val;
}
getValue(): number {
return this.value;
}
}
Baz.recordModule('B', 'Bar');
此时我发出tsc
编译成功。我也可以在没有失败的情况下将其打包 - 但它不起作用。收到的错误是:
TypeError:undefined不是对象(评估&#39; main_1.Baz.recordModule&#39;)
我不明白的是,如果我把它全部粘贴到一个文件中 - 它就可以了。
export class Baz {
static bucket = {};
private name: string;
constructor(a: string) {
this.name = a;
alert('constructor');
}
static recordModule(indexCode: string, objectName: string) {
Baz.bucket[indexCode] = objectName;
console.log("Module " + objectName + " recorded with index " + indexCode);
alert(objectName);
}
public createFoo(): Foo {
return new Foo(1);
}
public createBar(): Bar {
return new Bar(2);
}
}
export class Foo {
private value: number;
constructor(val: number) {
this.value = val;
}
getValue(): number {
return this.value;
}
}
Baz.recordModule('F', 'Foo');
export class Bar {
private value: number;
constructor(val: number) {
this.value = val;
}
getValue(): number {
return this.value;
}
}
Baz.recordModule('B', 'Bar');
如何成功地将类分成不同的文件,并使它像所有连接的类一样工作?
为了完整性,这是我的打字稿配置:
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"module": "commonjs",
"removeComments": true,
"pretty": true,
"skipLibCheck": true
},
"typeRoots": [
"node_modules/@types"
]
}
webpack.config.js
module.exports = [{
entry: './main.ts',
output: {
filename: 'main.js',
libraryTarget: "this",
},
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.js']
},
module: {
loaders: [
{test: /\.ts$/, loader: 'ts-loader'}
]
}
}];
非常感谢,(我正在努力学习TS和Webpack)!