2016-12-03 27 views
4

我有一些模块libnode_modules,我想要使用它。 我为此写了lib.d.ts我可以导入* .d.ts而不需要它吗?

文件看起来像:

/src/ 
    main.ts (imports `lib`) 
/types/ 
    lib.d.ts 

在文件main.ts我可以这样写代码:

/// <reference path="../types/lib.d.ts" /> 
import {some} from 'lib'; 

和它的作品。

但是当我尝试使用进口的环境声明文件:

import '../types/lib'; 
import {some} from 'lib'; 

它编译没有错误,但导致JS我能找到需要的文件:

require('../types/lib'); 
const lib_1 = require('lib'); 

有了错误丢失文件的运行时间../types/lib - 它只是一个没有生成文件的环境声明文件。

为什么编译器没有删除* .d.ts文件的导入?
我可以使用导入吗?或者我必须使用导入吗?

解决方案:

如果你不想使用reference指令, 你可以只添加必需* .d.ts的文件,包括你的tsconfig.json 。

我tsconfig.json是:

{ 
    "compilerOptions": { 
     "module": "commonjs", 
     "target": "es2015", 
     "lib": ["es2016"], 
     "noImplicitAny": true, 
     "noImplicitReturns": true, 
     "noImplicitThis": true, 
     "strictNullChecks": true, 
     "noFallthroughCasesInSwitch": true, 
     "noUnusedLocals": true, 
     "noUnusedParameters": true, 
     "noEmitOnError": true, 
     "newLine": "LF", 
     "forceConsistentCasingInFileNames": true, 
     "removeComments": true, 
     "declaration": false, 
     "sourceMap": false, 
     "outDir": "../build", 
     "types": [ 
      "node" 
     ] 
    }, 
    "files": [ 
     "index.ts" 
    ] 
} 

早期我想我.d.ts添加到types部分,但在这种情况下 TCS正试图找到node_modules /这个文件@类型目录。

的建议后,我试图添加文件files部分:

"files": [ 
     "index.ts", 
     "types/lib.d.ts" 
    ] 

它的作品,似乎是一个很好的解决方案。

回答

4

您不必定义import定义文件。

你可以手动/// <reference它。但正确的方法是通过文件tsconfig.json使其可用于编译器。

,其包括任何东西,但node_modulestsconfig.json一个例子:

{ 
    "compilerOptions": { 
     "module": "commonjs", 
     "target": "es5" 
    }, 
    "exclude": [ 
     "node_modules" 
    ] 
} 

documentation on tsconfig.json is here

+1

感谢您的建议! 我更喜欢用'files'而不是'exclude',但是你给了我正确的方向。 我更新了我的问题,添加了这个解决方案。 – Avol

+0

没有帮助,我得到了错误:无法找到模块'./img/logo_game_0.png'。 –

+0

如何确保它实际上找到了'd.ts'文件?我应该从使用JS库中的函数中得到错误,我没有在'd.ts'文件中声明',但我不是...... –

相关问题