使用 TypeScript 2.0 导入 js 文件

Import js file with TypeScript 2.0

摘要

我正在尝试从外部位置导入“.js”文件(即 node_modules)我正在尝试使用 commonjs 模块模式来执行此操作,但是 import 不想使用“.js”文件类型,直到我在同一文件夹中的“.js”文件附近添加“.d.ts”文件。

但问题是我不想用我的“.d.ts”文件影响任何 node_modules。我希望它位于另一个文件夹中,与 node_modules 分开,但一旦我这样做,打字稿编译器就会抛出错误:

例子

我有以下文件夹结构:

|- DTS
|   |- y.d.ts
|- main.ts
|- y.js

y.js有以下内容

module.export = function (x) {
    console.log(x);
};

y.d.ts有以下内容

export interface Y {
    (x): any;
}
declare let y: Y;
export default y;

main.ts有以下内容

import * as y from './y'

现在,当我尝试编译 main.ts 时:

tsc -m commonjs -t ES2015 main.ts

我会得到一个错误:

x.ts(1,20): error TS2307: Cannot find module './y'.

问题

如何导入“.js”文件并能够定义它的“.d.ts”声明,同时让两个文件位于不同的位置。


编辑

Here is the link to example project。请务必使用 TypeScript 2.0 版编译器。和上面的tsc命令查看错误。

being able to define it's ".d.ts" declarations while having both files located in different locations.

当给定 .js.d.ts 文件以及相关文件时,

import 遵循相同的模块解析过程。

注意:official recommendation for proving your type definitions 采用的方法与下面介绍的方法略有不同。 我相信下面的方法稍微好一些,因为 *.d.ts 文件实际上与最终产品相同。

在类型检查(构建时)期间,TypeScript 使用 *.ts 文件并且(大部分)忽略 *.js 文件。 让我举一个例子来激发(我相信)你的提议。 假设存在一个非常好的 JavaScript 库,可惜没有类型(例如 N3)。 已通过 npm 安装,因此:

npm install n3 --save

这是典型的添加到 ./node_modules/n3/... 和 project.json。 如前所述,类型不存在,需要手动添加。 为此,我创建了一个 ./@types/n3.d.ts 文件。 就我们的目的而言,定义实际上是什么并不是特别重要,但像下面这样的东西是一个好的开始:

declare namespace N3 {
}

declare module "n3" {
    export = N3;
}

现在回答你的问题。 更新'tsconfig.json':

...
"compilerOptions": {
    "typeRoots": [
      "node_modules/@types",
      "@types"
    ],
...
"paths": {
  "*": [
    ...
    "./@types/*"
  ]

仍然需要处理 运行 时间分辨率来定位相应的 *.js 文件,但这与您提出的问题不同。

作为参考,您可能会找到 What is new in TypeScript this discussion thread 有用。

这种方法在处理全局变量时效果很好,但在处理模块时效果不佳。

更新'tsconfig.json':

...
"paths": {
  "*": [
    ...
    "./@types/*"
  ],
  "foo": [ "./@types/foo.d.ts" ]
  },
 ...