TypeScript 找不到全局定义的 class

TypeScript cannot find class defined globaly

我有这个文件

routing.ts

class RouteConfig {
  // Some implementation
}

我是这样用的

app.module.ts

angular.module("ApplicationsApp", [
    "ApplicationsApp.Services",
    "ApplicationsApp.Clients",
    "ApplicationsApp.Application"])
    .config(RouteConfig);

然后我使用

导入之前的两个文件

index.ts

import "./scripts/routing.ts";
import "./scripts/app.module.ts"";

我正在使用 webpackts-loader,而 index.ts 是入口点之一。构建成功,但是当我 运行 它时,我得到这个错误

app.module.ts:5 Uncaught ReferenceError: RouteConfig is not defined
    at Object.<anonymous> (app.module.ts:5)
    at __webpack_require__ (bootstrap 755a82fd7c11e301b6c1:676)
    at fn (bootstrap 755a82fd7c11e301b6c1:87)
    at Object.<anonymous> (index.ts:4)
    at __webpack_require__ (bootstrap 755a82fd7c11e301b6c1:676)
    at fn (bootstrap 755a82fd7c11e301b6c1:87)
    at Object.defineProperty.value (events.js:302)
    at __webpack_require__ (bootstrap 755a82fd7c11e301b6c1:676)
    at logLevel (bootstrap 755a82fd7c11e301b6c1:722)
    at main.min.js:726

我给ts-loader的配置看起来像

{
  configFile: paths.resolveOwn('config/tsconfig.json'),
  compilerOptions: {
    target: 'ES5',
    module: 'commonjs',
    moduleResolution: 'node',
    sourceMap: true,
    strict: true,
    typeRoots: [
      paths.resolveOwn('node_modules/@types'),
      paths.resolveApp('node_modules/@types')
    ]
  }
}

你知道我做错了什么吗?我查看了几乎所有 tsconfig.json 选项,但找不到解决我问题的选项

问题

routing.ts 中你没有任何 export 也没有 import:对于 TypeScript,它是一个 script。但是你使用 Webpack 并且你 import 它:对于 Webpack,routing.ts 是一个 模块 。在编译时,class RouteConfig 可全局访问并且您的程序可以编译。但是,在 运行 时间,class RouteConfig 无法全局访问。

解决方案 1:旧方法,将 routing.js 作为脚本加载

您可以在单独的文件routing.js 中编译routing.ts。然后,在 HTML 代码中,必须从单独的标签 <script src="scripts/routing.js">.

加载编译文件

在此解决方案中,不要 import Webpack 捆绑的模块中的文件 routing.ts。只需确保在 tsconfig.json 中它可以被 TypeScript 编译器访问。

方案二:丑陋的方式,手动声明RouteConfig为全局变量

你可以这样做:

// routing.ts
class RouteConfig {
  // Some implementation
}
window["RouteConfig"] = RouteConfig;

然后,在 index.ts 中导入 routing.ts

// index.ts
import "./scripts/routing.ts";

因此,Webpack 确保 routing.ts 被执行。并且您的全局变量在 运行 时间可以访问。

注意:此解决方案基于误解。对于 Webpack 和 运行 时间,routing.ts 不是 script 而是声明全局变量的模块。对于 TypeScript(在编译时),它是一个以 window.

古怪且不受管理的东西结尾的脚本

解决方案 3:ES6 方式,所有模块,没有全局

以ES6方式,不创建任何全局变量。所有代码都在模块中。首先,您必须导出 class:

// routing.ts
export default class RouteConfig {
  // Some implementation
}

然后,您可以导入它:

// index.ts
import RouteConfig from "./scripts/routing.ts";

有关 ES6 模块的文档:ES6 in Depth: Modules