【发布时间】:2021-03-27 10:37:57
【问题描述】:
概述
我不熟悉在没有框架的情况下使用 TypeScript 和 PIXI.js。我曾经使用语言/库来工作,我们使用带有模块关键字的命名空间。我一直在尝试复制我们使用的设置,因为我认为它看起来比加载大量导入语句要好得多。
问题
当我在浏览器中运行我的代码时,我在 windows 检查器控制台中收到以下错误:
Uncaught TypeError: MyApp.AbstractModel is not a constructor
at Main../src/Main.ts.Main.createModel (Main.ts:16)
我发现和尝试的修复方法
我已经阅读了很多次找到的命名空间的打字稿文档here 和here,但看不到我哪里出错了。
最初我认为问题在于并非所有文件都被 webpack 加载,但我通过找到的建议修复了这个问题 here(即“require.context()”),但错误仍然存在。
我尝试从主文件导入命名空间(将 Main 中的内容复制到 Game.ts,并将以下内容放入 Main.ts)
require.context("../src/", true, /\.ts$/);
/// <reference path="Game.ts" />
class Main {
constructor() {
console.log("Main.constructor()");
new MyApp.Game();
}
}
new Main();
结构
我的文件结构如下:
stack-overflow-example
| - .idea
| - dev
| | - dts
| | | <all .d.ts files from tsc compilation>
| | - js
| | | <all .js files and accompanying .js.map files from compiled .ts files>
| | - index.html
| - node_modules
| - src
| | - graphics
| | | - pixi-manager.ts
| | - model
| | | - AbstractModel.ts
| | - Main.ts
| | - refs.ts
| package.json
| package-lock.json
| tsconfig.json
| webpack.config.js
守则
index.html
<!DOCTYPE html>
<html>
<head>
<title>stack-overflow-example</title>
</head>
<body>
<script src="js/Bundle.js" type="text/javascript"></script>
</body>
</html>
维护.ts
/// <reference path="refs.ts" />
require.context("../src/", true, /\.ts$/);
namespace MyApp {
export class Main {
public static instance: Main = new Main();
public model: AbstractModel;
constructor() {
console.log("Main.constructor()");
this.createModel();
}
protected createModel(): void {
this.model = new AbstractModel();
}
protected addComponent(view: PIXI.DisplayObject): void {
PixiManager.instance.stage.addChild(view);
}
public getModel(): AbstractModel {
return this.model;
}
}
}
AbstractModel.ts
/// <reference path="../refs.ts" />
namespace MyApp {
export class AbstractModel {
constructor() {
console.log("AbstractModel.constructor()");
}
}
}
refs.ts
/// <reference path="graphics/pixi-manager.ts" />
/// <reference path="model/AbstractModel.ts" />
/// <reference path="Main.ts" />
package.json
{
"name": "my-game",
"version": "1.0.0",
"description": "",
"main": "Main.ts",
"scripts": {
"start": "webpack-dev-server --content-base dev/ --inline --hot"
},
"devDependencies": {...}
}
tsconfig.json
{
"compilerOptions": {
"outDir": "./dev/js/",
"module": "commonjs",
"target": "ES5",
"sourceMap": true,
"declaration": true,
"declarationDir": "./dev/dts"
},
"include": ["./src/*.ts"]
}
webpack.config.js
var path = require("path");
module.exports = {
entry: {
namespace: "./src/Main.ts"
},
mode: "development",
devtool: "source-map",
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
path: path.resolve(__dirname, "dev/js/"),
filename: "js/Bundle.js"
}
};
问题
如何在保持命名空间样式而不是使用模块的同时修复“MyApp.AbstractModel 不是构造函数”错误?
非常感谢您的所有帮助,感谢您的宝贵时间。
【问题讨论】:
标签: typescript webpack webpack-dev-server pixi.js tsc