【问题标题】:Import in declaration files not recognized as module在不被识别为模块的声明文件中导入
【发布时间】:2021-07-02 11:21:47
【问题描述】:

我正在将当前应用程序中的所有 typescript 接口提取到一个 npm 包中,因为我正在构建一个将使用相同接口和枚举的微服务架构。

我遇到的问题是某些接口需要第三方类型,我试图将其导入我的声明类型,但它会引发错误。

Cannot use import statement outside a module

我在输入时没有收到任何警告,但在我的实际应用程序中上传更改和更新 npm 包时。

这是我的index.d.ts的精简版

import { ObjectId } from 'mongodb'
    
declare module MyApp {
  export interface MyInterface {
    _id: ObjectId
    firstName: string
    lastName: string
    ...
  }
}

这是我的tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

我试过了

declare module MyApp {
  import { ObjectId } from 'mongodb'

  export interface MyInterface {
    ...

这给了我

Import declarations in a namespace cannot reference a module

我也试过

import { ObjectId } from 'mongodb'

export interface MyInterface {
  ...

但是什么也没发生。我尝试将declare module 更改为declare namespace。什么都没有发生。

我在package.json 中尝试了使用和不使用"type": "module",但没有任何反应。

【问题讨论】:

  • 可以添加根目录 "compilerOptions": { "rootDir": "./", }
  • 不幸的是,没有任何改变@VENKATESHCHAVVAKULA
  • "compilerOptions": { "target": "es5", "module": "commonjs", "lib": [ "es6" ], "allowJs": true, "outDir": " build", "rootDir": "./", "strict": true, "noImplicitAny": true, "esModuleInterop": true, } 你可以试试这个吗
  • 问题出在其他地方,请检查我的答案,并感谢您的帮助 :)

标签: typescript


【解决方案1】:

看来一切都已正确配置。这是我的应用程序中的错误导入。

这是解决办法

// Old
import MyApp from '@org/my-app'

// Fix
import { MyApp } from '@org/my-app'

当我尝试使用 MyApp.MyInterface 访问声明文件中的任何内容时,它崩溃了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2017-09-25
    • 1970-01-01
    • 2015-04-28
    • 2021-12-03
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多