Can I import * .d.ts and not require it?

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

The files look like this:

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

In the main.ts 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 the environment declaration file:

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

it compiles without errors, but as a result of JS, I can find the one required for this file:

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

With an error during execution of the missing file ../types/lib is simply an environmental declaration file without a resulting file.

Why did the compiler not delete the import of the * .d.ts file?
Can I use import in any way, or use the link instead?

Decision:

If you do not want to use the reference directives, you can simply add the necessary * .d.ts files to the files included with 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" ] } 
I used to try to add the .d.ts section to types , but in this case tcs tries to find this file in the node_modules / @ types directory.

After the sentence, I tried to add the file to the files section:

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

This works and seems like a good solution.

+5
source share
1 answer

You do not need to import the definition file.

You can manually select /// <reference . But the right way is to simply make it available to the compiler via the tsconfig.json file.

An example of tsconfig.json , which includes everything except node_modules :

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

The documentation for tsconfig.json is here .

+4
source

Source: https://habr.com/ru/post/1260764/


All Articles