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.