18

Abstract

I'm trying to import ".js" file from an external location (i.e. node_modules) I'm trying to do this using commonjs module pattern, however import wouldn't want to work with ".js" file types until I add ".d.ts" file near ".js" file in the same folder.

But the problem is that I wouldn't want to affect any node_modules with my ".d.ts" files. I want it to be located in another folder, separate from node_modules but as soon as I do that, typescript compiler throws an error:

Example

I have the following folder structure:

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

y.js has the following content

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

y.d.ts has the following content

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

main.ts has the following content

import * as y from './y'

Now when I'm trying to compile main.ts with:

tsc -m commonjs -t ES2015 main.ts

I will get an error:

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

Question

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


Edit

Here is the link to example project. Be sure to use TypeScript version 2.0 compiler. And the tsc command above to see the error.

4

2 回答 2

17

注意:证明您的类型定义的官方建议采用的方法与下面介绍的方法略有不同。我相信下面的方法稍微好一些,因为 *.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 文件,但这与您提出的问题不同。

作为参考,您可能会发现TypeScript 中的新增功能此讨论线程很有用。

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

更新“ tsconfig.json ”:

...
"paths": {
  "*": [
    ...
    "./@types/*"
  ],
  "foo": [ "./@types/foo.d.ts" ]
  },
 ...
于 2016-08-30T15:34:09.080 回答
0

能够在两个文件位于不同位置的同时定义它的“.d.ts”声明。

import.js当给定带有相关文件的or.d.ts文件时,遵循相同的模块解析过程。

于 2016-07-19T01:52:58.957 回答