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.
d. ts files are treated as an ambient module declarations only if they don't have any imports. If you provide an import line, it's now treated as a normal module file, not the global one, so augmenting modules definitions doesn't work. So the line import("./user").
Key Differences Between Require and Import Require is Nonlexical and Import is Lexical. Requires to stay where they have put the file, and imports get sorted to the top of the file. Import is always run at the very beginning of the file and can't be run conditionally.
The "d. ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With