【问题标题】:d.ts declare module not work when import third party libsd.ts 声明模块在导入第三方库时不起作用
【发布时间】:2020-07-02 21:23:48
【问题描述】:

通过导入将d.ts依赖中的模块声明为第三方模块时,出现一些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"]
}

打字/index.d.ts

import * as moment from 'moment';

declare module 'someModule' {
    export function test(x: string): moment.CalendarKey;
}

但没有导入工作正常

declare module 'someModule' {
    export function test(x: string): string;
}

有什么问题?

【问题讨论】:

    标签: typescript visual-studio-code


    【解决方案1】:

    您需要将时刻导入放在declare module下:

    declare module 'someModule' {
        import * as moment from 'moment';
        export function test(x: string): moment.CalendarKey;
    }
    

    这是必需的,因为如果文件具有顶级导入或导出 (docs),Typescript 具有不同的行为:

    在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级导入或导出的文件都被视为一个模块。相反,没有任何顶级导入或导出声明的文件被视为脚本,其内容在全局范围内可用(因此也可用于模块)。

    当您在顶层添加导入时,它会将您的文件转换为模块,并且声明的范围仅限于该文件。当您在声明中移动导入时,Typescript 将文件视为脚本,并且声明可用于项目中的其他文件。

    另外,请参阅此问题的类似问题:

    How to include ambient module declarations inside another ambient module?

    【讨论】:

    • 但不能在一个文件中导入重复 ``` 声明模块 'webpack-shell-plugin'{ import { Plugin, Compiler } from 'webpack'; } 声明模块 'write-file-webpack-plugin' { import { Plugin, Compiler } from 'webpack'; } ```
    • 这是为我解释的!我有一个带有导出命名函数的声明模块。在顶层添加导入时,命名函数对消费者“消失”。一旦我在声明中移动导入,它就会重新出现。
    猜你喜欢
    • 2023-04-01
    • 2017-10-18
    • 1970-01-01
    • 2021-12-06
    • 2021-12-13
    • 1970-01-01
    • 2017-05-07
    • 2021-10-11
    相关资源
    最近更新 更多