[英]d.ts declare module not work when import third party libs
There are some Vscode tips "module not found" when declare module in d.ts dependency an third party module by import, is there any solution for it?在d.ts依赖中通过import声明模块为第三方模块时,Vscode提示“找不到模块”,有什么解决办法吗?
tsconfig.json配置文件
{
"compilerOptions": {
"outDir": "./dist/",
"target": "es5",
"lib": ["esnext", "dom.iterable","dom", "scripthost", "es2015.symbol"],
"sourceMap": true,
"noImplicitAny": true,
"jsx": "react",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"allowJs": true,
"module": "commonjs",
"isolatedModules": false,
"esModuleInterop": true
},
"include": ["src/**/*","typings/*"],
"exclude": ["node_modules"]
}
typings/index.d.ts打字/index.d.ts
import * as moment from 'moment';
declare module 'someModule' {
export function test(x: string): moment.CalendarKey;
}
but without import works fine但没有导入工作正常
declare module 'someModule' {
export function test(x: string): string;
}
what's problem?什么问题?
You need to put moment import under the declare module
:您需要将 moment import 放在declare module
:
declare module 'someModule' {
import * as moment from 'moment';
export function test(x: string): moment.CalendarKey;
}
This is needed because Typescript has different behavior if a file has top-level imports or exports ( docs ):这是必需的,因为如果文件具有顶级导入或导出( docs ),则 Typescript 具有不同的行为:
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级导入或导出的文件都被视为一个模块。 Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).相反,没有任何顶级导入或导出声明的文件被视为脚本,其内容在全局范围内可用(因此也对模块可用)。
When you add an import at the top level, it turns your file into a module and declarations become scoped to this file only.当您在顶层添加导入时,它会将您的文件转换为模块,并且声明的范围仅限于此文件。 When you move the import inside declaration, Typescript treats the file as script and declarations become available to other files in the project.当您在声明中移动导入时,Typescript 将文件视为脚本,并且声明可用于项目中的其他文件。
Also, see this question with a similar issue:另外,请参阅具有类似问题的此问题:
How to include ambient module declarations inside another ambient module? 如何在另一个环境模块中包含环境模块声明?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.