外部模块的 .d.ts 声明的捆绑

问题描述 投票:0回答:1

我的目的是将我自己编写的 TS 代码的 TypeScript 定义与驻留在 node_modules 中的外部模块的定义捆绑在一起。背后的原因是我需要将这些联合定义提供给基于 Web 的 TS 代码编辑器 (MonacoEditor) 以允许代码完成。

到目前为止,我已经得到了一些与 rollup-plugin-ts 一起使用的东西,并且还在 rollup-plugin-ts github 问题 #164 中提出了以下问题,到目前为止没有任何答案。我也尝试过 rollup-plugin-dts,但无法让它工作得更好。然而,我对框架的选择持开放态度(不需要汇总),我只需要自定义代码、节点内部模块和外部模块的定义,将其捆绑到仅导出的 single .d.ts 文件中入口点 .ts 文件导出了什么。

我工作得很好:

  • 将 .ts 转换为 .js 并捆绑到单个 .js 文件中(注意:我不需要 .js 文件;最后我会打开 emitDeclarationOnly,但这现在不太相关)。这适用于自定义代码、节点内部模块(例如“path”)和外部模块(例如“typeorm”)
  • 将 .ts 转换为 .d.ts 用于自定义代码

什么还不起作用:

  • 将节点内部和外部模块的 .ts 转换为 .d.ts 仅引用模块但我希望将它们内联在同一个 .d.ts 文件中

现在有什么方法可以强制 rollup-plugin-ts (或使用任何其他工具)内联外部类型定义?

作为参考,我创建了以下最小存储库,包括输出 .js 和 .d.ts:https://github.com/sumbricht/rollup_dts_example。实际上,它将包含大约 100 个外部模块的定义,因此手动管理是不可行的;然而,也欢迎替代的自动化方法:-)。

主要文件下方: rollup.config.js:

import ts from 'rollup-plugin-ts'
import commonjs from '@rollup/plugin-commonjs'
import nodeResolve from '@rollup/plugin-node-resolve'
import polyfill from 'rollup-plugin-polyfill-node'

const config = [
    {
        input: "./src/entrypoint.ts",
        output: [{ file: "./dist/entrypoint.js", format: "es" }],
        plugins: [
            polyfill(),
            commonjs(),
            nodeResolve(),
            ts({
                tsconfig: './tsconfig.json',
                exclude: [],
            })
        ],
    },
];

export default config;

tsconfig.json:

{
  "compilerOptions": {
    /* Language and Environment */
    "target": "ESNext",

    /* Modules */
    "module": "ESNext",
    "moduleResolution": "node",
    "typeRoots": ["node_modules/@types"],
    "types": ["node"],

    /* Emit */
    "declaration": true,
  },
  "exclude": []
}

入口点.ts:

// code by myself: nicely reflected in .js and .d.ts
export { Foo } from './foo'

// node-internal code: nicely reflected in .js but as external reference in .d.ts
export { dirname } from 'path'

// external module: nicely reflected in .js but as external reference in .d.ts
export { createConnection } from 'typeorm'

entrypoint.js:

class Foo {
    foo;
    constructor(foo) {
        this.foo = foo;
    }
    printFoo() {
        console.log(this.foo);
    }
}

// code from 'path' and 'typeorm' (cut for brevity)

export { Foo, createConnection$1 as createConnection, dirname };

入口点.d.ts:

declare class Foo {
    private foo;
    constructor(foo: string);
    printFoo(): void;
}
export { Foo };
export { dirname } from 'path';
export { createConnection } from 'typeorm';
typescript webpack rollupjs typescript-declarations
1个回答
0
投票

我有一个非常相似的用例。您可能想查看

tsup
--dts-resolve
选项。它允许您解析外部类型并将其捆绑到单个
.d.ts
文件中。如果您只需要
--dts-only
文件,您可以添加
.d.ts
选项。

官方文档没有太多相关信息,但是这个博客可以给你一个想法。

© www.soinside.com 2019 - 2024. All rights reserved.