How to solve the “Could not find a declaration file for module” error using my own declaration file?

∥☆過路亽.° 提交于 2021-01-28 08:31:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!