问题
I have a test project in which I'm testing type definition files. The project has one file called index.ts
which looks like this:
import i18nFu = require("gettext.js");
The gettext.js package was installed using Node.js like this: npm install gettext.js
VS Code displays the following error message for the line above:
Could not find a declaration file for module 'gettext.js'.
'SOME_PATH/gettext.js' implicitly has an 'any' type.
Try 'npm install @types/gettext.js' if it exists or add a new declaration (.d.ts) file containing "declare module 'gettext.js';"
Installing the @types/gettext.js
module does fix the problem. But I'm curious so I didn't stop there. I removed the @types/gettext.js
module again and tried to create the declaration file myself.
I create a subfolder called types/gettext.js
in my project's folder and copied the content of the old node_modules/@types/gettext.js
folder into it. I also added a typeRoots
entry to my tsconfig.json
file so it looks like this:
{
"compilerOptions": {
"lib": ["ES2017"],
"module": "commonjs",
"strict": true,
"target": "es5",
"typeRoots": ["./types", "./node_modules/@types"],
},
"files": ["test.ts"]
}
But the error message won't disappear. Replacing the content of the types/gettext.js/index.d.ts
file (which you can see here) with declare module 'gettext.js'
(as suggested by the error message) does remove the error. But that is not a solution for having types. What am I missing?
PS: I'm not interested in work around hack solutions like using ts-ignore
or setting noImplicitAny
to false
.
回答1:
I solved the problem by setting the baseUrl
compiler option. Interestingly I don't need the typeRoots
option at all now to compile and run successfully. This is the new tsconfig.json
file:
{
"compilerOptions": {
"lib": ["ES2017"],
"module": "commonjs",
"strict": true,
"target": "es5",
"baseUrl": "./types"
},
"files": ["tests.ts"]
}
I hope this helps someone running into the same problem.
来源:https://stackoverflow.com/questions/61258923/how-to-solve-the-could-not-find-a-declaration-file-for-module-error-using-my-o