首页 > 解决方案 > 在 npm 包中使用声明文件时如何解析声明文件中的绝对路径

问题描述

我在打字稿中使用绝对路径。它编译得很好,但是当我尝试将已编译的 JS 代码与声明一起发布到 npm 注册表,然后将包作为依赖项包含到第二个包时 - tsc 抱怨它找不到模块声明。这是在 npm 上发布的第一个包中的 tsconfig.json:

{
    "compilerOptions": {
        "outDir": "out",
        "target": "ESNext",
        "strict": true,
        "strictNullChecks": false,
        "baseUrl": "src",
        "rootDir": "src",
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "allowUnusedLabels": false,
        "moduleResolution": "node",
        "declaration": true,
        "esModuleInterop": true,
        "declarationDir": "types",
        "lib": [
            "DOM",
            "ES2015"
        ]
    },
    "include": [
        "src"
    ]
}

以及主要生成的 cookie.d.ts 文件的示例代码:

import { Attributes } from 'Attributes';
import { KeyValueEntry } from 'KeyValyeEntry';
import { TypedMap } from 'TypedMap';
import { ValueEntry } from 'ValueEntry';

export function get(key: string): string;
// ...

以及错误消息的示例: cookie.d.ts:1:28 - error TS2307: Cannot find module 'Attributes' or its corresponding type declarations. 因此 tsc 无法解析声明文件中的绝对路径,但是当我将路径重写为相对路径时很好理解,即“./Attributes”而不是“Attributes”。谷歌搜索和搜索文章没有给我答案。有没有办法解决这个问题并在包中保留绝对路径?

标签: typescriptnpm

解决方案


推荐阅读