0

我有这个文件

路由.ts

class RouteConfig {
  // Some implementation
}

我这样使用

app.module.ts

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

然后我使用导入之前的两个文件

索引.ts

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

我正在使用webpackandts-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选项,但找不到解决我问题的选项

4

1 回答 1

5

问题

因为routing.ts你什么都export没有import:对于 TypeScript,它是一个脚本。但是你使用 Webpack 并且你使用import它:对于 Webpack,routing.ts是一个模块。在编译时,可以全局访问该类RouteConfig,并且您的程序可以编译。但是,在运行时,该类RouteConfig不可全局访问。

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

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

在这个解决方案中,不要使用 Webpack 捆绑的模块import中的文件routing.ts。只需确保tsconfig.jsonTypeScript 编译器可以访问它。

解决方案2:丑陋的方式,手动声明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 方式中,不要创建任何全局变量。所有代码都在模块中。首先,您必须导出您的课程:

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

然后,您可以导入它:

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

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

于 2017-08-31T08:34:36.033 回答