Exclude/overwrite npm 提供的类型

Exclude/overwrite npm-provided typings

我有一个 npm 包,里面写得很糟糕,打字已经过时了。我已经编写了自己的打字,现在我想知道我是否可以以某种方式从 npm 包中排除原始打字。不是简单的接口扩展,原来的基本都是垃圾

使用 tsconfig.json 中的排除列表当然不能用于此目的,因为即使您排除该文件夹,它仍然会从 node_modules 加载文件。

您可以使用 tsConfig 中的路径选项获得所需的行为 它可能看起来像这样:

{
    "compilerOptions": {
       ...
        "paths": {
            "*": [
                "src/*",
                "declarations/*"
            ]
        }
    },
    ...
}

使用此配置,typescript 在 src(应该有所有应用程序源)和声明中查找模块,在声明文件夹中,我通常会放置额外需要的声明。

要覆盖节点模块的类型,有两个选项:

  1. 在声明文件夹中放置一个与模块同名的文件夹,其中包含一个名为 index.d.ts 的文件,用于打字

  2. 在声明文件夹中放置一个与模块同名的声明文件

作为工作示例,您可以查看此存储库 https://github.com/kaoDev/react-ts-sample

Bernhard Koenig的重要提示:

The order of the paths matters. I had to put the path with my overrides before the path with the original type definitions so my overrides get picked up first. – Bernhard Koenig

在您的 src 下创建 node_modules 文件夹,然后将您要覆盖的模块类型放入其中:

├── node_modules
│   └── ...
│
└── src
    ├── index.ts
    ├── ... your codes ...
    │
    └── node_modules
        └── <module-to-be-overwritten>
            └── index.d.ts

无需修改tsconfig.json中的compilerOptions

阅读 TypeScript 如何解析模块 部分 https://www.typescriptlang.org/docs/handbook/module-resolution.html