我的项目中有 JS/TS 代码库。一些文件看起来像:
import Something from '@some-lib/things/something'; // index.jsx file here
const someFunction = () => {
// do something with "Something"
};
在 VS Code 和 tsc 结果中我有错误:Could not find a declaration file for module '@some-lib/things/something'.
'/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx' implicitly has an 'any' type.
Try
npm install ...
if it exists or add a new declaration (.d.ts) file containingdeclare module '@some-lib/things/something';
我尝试通过创建文件
src/@types/@some-lib/index.d.ts
添加定义包含以下内容:declare module '@some-lib/things/something' {
const Something: (props: React.SVGProps<SVGSVGElement> & {
size?: number,
color?: string,
inline?: boolean,
className?: string,
}) => React.ReactElement;
export default Icon;
}
但我得到这个错误:Invalid module name in augmentation.
Module '@some-lib/things/something' resolves to an untyped module at '/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx', which cannot be augmented.
请帮我。如何从带有子目录/子模块的 npm 声明 JS 库的 TypeScript 类型?
最佳答案
我找到了解决方案。
如果要创建d.ts
对于来自 npm-modules 的 js/jsx 文件,您可以像这样导入:
// this is reference to ./node_modules/@some-lib/things/something/index.js
import Something from '@some-lib/things/something'
你需要paths
给您的tsconfig.json
: {
"compilerOptios": {
// ...
"baseUrl": ".", // just require for "paths"
"paths": {
"@some-lib/*": ["src/types/some-lib"] // 'src/types' is just for example
}
}
}
src/types/@some-lib/things/something.d.ts
内容:declare module '@some-lib/things/something' { // equal to import
const Something = number; // number just for example
export = Something;
}
据我了解,您的d.ts
中的文件路径应与 node_modules
中的路径相同, 除了它的根从 src/types/
开始例如。我真的希望这会对你有所帮助,祝你好运!
关于javascript - 如何从 npm 声明 javascript 子模块的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63016869/