【问题标题】:relative import cannot resolve to an ambient module相对导入无法解析为环境模块
【发布时间】:2018-01-28 20:24:30
【问题描述】:

根据打字稿文档(https://www.typescriptlang.org/docs/handbook/module-resolution.html):

相对导入是相对于导入文件解析的,并且 无法解析为环境模块声明。

还有:

例如,像 import { b } from "./moduleB" in /root/src/moduleA.ts 将导致尝试以下操作 定位“./moduleB”的位置:

/root/src/moduleB.ts
/root/src/moduleB.tsx
/root/src/moduleB.d.ts
/root/src/moduleB/package.json (if it specifies a "typings" property)
/root/src/moduleB/index.ts
/root/src/moduleB/index.tsx
/root/src/moduleB/index.d.ts"

/root/src/moduleB.d.ts 行在我看来是用于解决相对导入“./moduleB”的环境模块声明 -> 正是文档否认它所做的.

是我遗漏了什么还是文档有误?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    简答

    /root/src/moduleB.d.ts 这行在我看来是环境模块声明...我在这里遗漏了什么还是文档有误?

    你在这里遗漏了一些东西。 moduleB.d.ts 不是环境模块声明。这是一个包含moduleB 环境模块声明的文件示例。

    // someFile.d.ts 
    
    declare module "moduleB" {
        export class b { }
    }
    

    declare 关键字指定环境声明。

    一些细节

    关于环境这个词,the documentation says

    我们将未定义实现的声明称为“环境”。通常,这些是在 .d.ts 文件中定义的。

    环境声明包括但不限于环境模块声明。包含环境声明的 .d.ts 文件不是环境模块声明,也不一定包含环境模块声明。

    例如,以下 greeter.d.ts 文件包含环境类声明,但它不是环境模块声明。

    // greeter.d.ts
    
    declare class Greeter {
        constructor(greeting: string);
        greeting: string;
    }
    

    以下foobar.d.ts 文件包含两个环境模块声明“foo”和“bar”,但文件本身不是环境模块声明。

    // foobar.d.ts
    
    declare module "foo" {       
        export function doFoo(foo: string): string;
    }
    
    declare module "bar" {
        export function doBar(bar: string): string;
    }
    

    您最初引用的文档指出,"./foo" 的相对导入无法解析为该模块的上述环境声明。

    更多详情

    见:https://www.typescriptlang.org/docs/handbook/modules.html

    另见:https://github.com/Microsoft/TypeScript-Handbook/issues/180

    另请参阅:https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html

    【讨论】:

    • 嗨,谢谢,但我仍然很困惑。 foob​​ar.d.ts 文件包含两个环境模块声明,与 Ambient Modules 部分中typescriptlang.org/docs/handbook/modules.html 作为示例给出的 node.d.ts 非常相似。也几乎与您所说的 someFile.d.ts 相同,它是环境模块。为什么 foobar.d.ts 本身不是环境模块声明?
    • @adrhc foobar.d.ts 包含两个环境模块声明,但 foobar.d.ts 不是环境模块声明。那是因为环境声明不是文件。环境声明是使用declare 关键字的语句。同样,someFile.d.ts 包含环境模块声明,但该文件不是环境模块声明,因为它是一个文件。此外,node.d.ts 文件不是环境模块声明;相反,它包含两个环境模块声明 "url""path"
    • 好的,那么我的问题中最有可能的是/包含/root/src/moduleB.d.ts?在考虑“最有可能”的文档摘录时也要考虑:“我们将未定义实现的声明称为“环境”。通常,这些声明是在 .d.ts 文件中定义的。”
    • @adrhc 如果我们把someFile.d.ts的内容放到moduleB.d.ts,我们import * as moduleB from "./moduleB",编译器会尝试在moduleB.d.ts定位moduleB,但是找不到那里有一个模块,因为文件中没有顶级导出/导入,并且因为它会忽略环境模块声明。
    • @adrhc 另外,当使用import * as moduleB from "moduleB" 时,这不会解析为moduleB.d.ts,因为它是非相对导入(您正确地说明了)。要使用非相对导入来导入环境模块,我们可以先执行/// <reference path="moduleB.d.ts"/>,在这种情况下我们可以使用非相对导入。
    猜你喜欢
    • 2023-03-15
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多