12

I have some module lib in node_modules and I want to use it. I wrote lib.d.ts for this.

Files looks like:

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

In file main.ts I can write this code:

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

And it works.

But when I try to use import for ambient declaration file:

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

it compiles without errors, but in resulting JS I can find require for this file:

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

With error in runtime of missing file ../types/lib – it's just an ambient declaration file without resulting file.

Why compiler did not remove import of *.d.ts file?
Can I use import somehow, or I must use reference instead?

Solution:

If you don't want to use reference directives, you can just add required *.d.ts to files, included by your tsconfig.json.

My tsconfig.json was:

{ "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" ] } 

Early I tried to add my .d.ts to types section, but in this case tcs is trying to find this file in node_modules/@types directory.

After suggestion I tried to add file in files section:

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

It's works and seems as a good solution.

1 Answer 1

11

You don't have to import an ambient definition file.

You can manually /// <reference it. But the right way is just to make it available for the compiler through the file tsconfig.json.

An example of tsconfig.json that includes anything but node_modules:

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

The documentation on tsconfig.json is here.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for suggestion! I prefer to use files instead of exclude, but you give me the right direction. I updated my question, adding this solution.
No help for me i got err: Cannot find module './img/logo_game_0.png'.
How do I make sure that it's actually found the d.ts file? I should be getting errors from using functions in the JS library that I did not declare in the d.ts file, but I'm not...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.