使用 TypeScript 声明 RequireJS 依赖项

Declaring RequireJS dependencies with TypeScript

我正在使用 TypeScript 和 RequireJS。如下图所示,我使用 RequireJS 配置定义了一些导入;当然,这些进口商品来自 <script> 标签:

TypeScript 看不到这些声明,所以我想将它们声明为全局变量或其他东西,以避免转译错误。 在这种情况下最好的做法是什么?一切似乎 运行 都很好,但我确实遇到了更多的编译错误,当然还有到处都是红色语法高亮显示。

在第一张图片中我们看到 requirejs 没有被识别,在下图中我们也看到 TypeScript 不知道 'redux' 是什么,(但它在 RequireJS 配置中) .

所以我想做的是告诉 TypeScript 以下依赖项:requirejs、redux、react、rxjs、socketio 等

所以部分问题是我需要 运行:

npm install -D @types/requirejs
npm install -D @types/redux

然后在我的 tsconfig.json 中添加:

  "types": [
      "node",
      "lodash",
      "react",
      "react-dom",
      "redux",
      "react-redux",
      "async",
      "requirejs"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],

而且,为了解决 TypeScript 无法理解 <script> 标签依赖项来自 front-end 的问题,看来我们可以这样做:

https://weblog.west-wind.com/posts/2016/Sep/12/External-JavaScript-dependencies-in-Typescript-and-Angular-2

De-referencing Globals In order to keep the Typescript compiler happy and not end up with compilation errors, or have a boat load of type imports you may only use once or twice, it's sometimes easier to simply manage the external libraries yourself. Import it using a regular script tag, or packaged as part of a separate vendor bundle and then simply referenced in the main page.

So rather than using import to pull in the library, we can just import using tag as in the past:

Then in any Typescript class/component where you want to use these libraries explicitly dereference each of the library globals by explicitly using declare and casting them to any:

declare var redux:any; 
declare var socketio: any;