繁体   English   中英

在 mono-repo 中仅从命名空间/类型 NPM 模块自动导入 Typescript 命名空间

[英]Automatically import Typescript namespace from namespace/type only NPM module in mono-repo

I have a number of private repositories that use the same Typescript types repeatedly so instead of copying them from one project to another, I have created a private NPM package that houses all of these shared types under a Typescript namespace. 如果使用共享类型,每个项目都会安装 NPM package。

索引.d.ts

export * as v1_6 from './types/version1_6';

export as namespace SharedNamespace;

使用这些类型的项目之一是具有以下项目结构的无服务器单一存储库:

package.json
tsconfig.json
|_ lib
|_ services
    |_ service1
    |_ service2
    |_ service3
    |_ service4
    |_ serviceX

其中 tsconfig.json 在父目录中,然后在services子目录中有几个无服务器项目,其中只有service1安装了私有 NPM 类型。

当我尝试在service1项目中使用命名空间时,出现错误:

Cannot find namespace 'SharedNamespace'.

我认为我得到的原因有两个:

  1. 我们的类型不在默认的./node_modules/@types位置。
  2. 由于我们的 NPM 模块只是 Typescript 命名空间,因此我们从不在项目的任何地方import

我的问题是,将它包含在我们的全局类型 scope 中的最佳方法是什么?

我的第一次尝试是在service1目录中使用自定义文件扩展基本tsconfig.json文件:

{
  "compilerOptions": {
    "typeRoots": [
      "../../node_modules/@types",
      "./node_modules/@types",
      "./node_modules/@myOrg/privateTypes"
    ]
  },
  "extends": "../../tsconfig.json"
}

但即使在我得到同样的错误之后。

但是,如果我在需要的地方手动导入命名空间,错误就会消失。 理想情况下,我们不必一直导入它。

更新 1

如果我使用以下tsconfig.json

{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@myOrg/privateTypes"
    ]
  },
  "extends": "../../tsconfig.json"
}

我现在收到错误Cannot find type definition file for 'types'. The file is in the program because: Entry point for implicit type library 'types'. Cannot find type definition file for 'types'. The file is in the program because: Entry point for implicit type library 'types'.

但是在私有 NPM 模块的package.json中:

  "main": "",
  "types": "index.d.ts",
  "typeScriptVersion": "3.9.7",

并在项目目录中:

私有 NPM 模块目录

所以我不确定为什么它找不到那个文件?

我今天遇到了完全相同的问题。 好吧,那是一年多之后的事了,我希望你在写这个问题后找到了合适的答案。

试试tsconfig.json中的include选项:

{
  "include": [
    ".",
    "./node_modules/@myOrg/privateTypes/index.d.ts"
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM