在 TypeScript 生成的声明文件中,排除内部导出的类型

dx_*_*_dt 6 typescript tsc tsconfig webpack typescript-declarations

我正在写一个面试问题。我通过创建“Http Client”包来模拟后端服务器。我希望在文件中公开我的一些类型.d.ts,以便受访者了解上下文,但大多数类型我不这样做,因为它们会暴露模拟的内部工作原理,并为受访者提供一些我希望他们生成的类型。

src/index.ts

import myPackageExport from `./my-package-export`;
export * from `./public-types`;
export { MyPackageExport } from `./my-package-export`;

export default myPackageExport;
Run Code Online (Sandbox Code Playgroud)

我想简单地在我tsconfig.json和/或我webpack.config.js喜欢的地方设置一些东西:

tsconfig.json

{
  "compilerOptions": {
    // ...
    "noEmit": true, // I've also tried `false`
    "declartion": true,
    "emitDeclarationOnly": true,
    "rootDir": "./src",
    "outDir": "./lib",
  },
  "include": [ "./src/index.ts" ],
  // ...
}
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

// ...

module.exports = {
  entry: path.join(__dirName, 'src/index.ts'),
  output: {
    fileName: 'index.js',
    path: path.join(__dirName, 'lib'),
  },
  // ...
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [ 'ts-loader' ],
      },
    ],
  },
  resolve: {
    extensions: [ '.js', '.ts' ],
  },
  plugins: [
    // some fancy declaration plugin here
  ],
};
Run Code Online (Sandbox Code Playgroud)

当然,这是非常周到的,它会为 的整个依赖关系图index.ts(即整个项目)生成声明。通常这是我们想要的,但就我而言不是。

一个更简单的解决方案是这样的// @ts-exclude-declaration,我可以在每个我想要排除的类型的文件前面添加,但据我所知,不存在这样的东西。

我当前的解决方法是添加/修改三个文件:

src/public-types/index.ts(修改的)

export * from './my-public-types1';
// ...

export interface MyPackageExport {
  // ...
}

declare const myPackageExport: MyPackageExport;

export default myPackageExport;
Run Code Online (Sandbox Code Playgroud)

tsconfig.types.json(添加)

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    // ...
    "declaration": true,
    "emitDeclarationOnly": true,
    "srcRoot": "./src/public-types",
    "outDir": "./lib",
  },
  "include": [ "./src/public-types/index.ts" ],
}
Run Code Online (Sandbox Code Playgroud)

package.json(显然是修改过的)

{
  "scripts": {
    "build": "webpack --mode production && tsc -p tsconfig.types.json",
    // ...
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud)

这可行,但远非优雅。

有想法吗?

dx_*_*_dt 0

tsconfig 有一个stripInternal选项,允许您使用 JSDoc@internal标记从 .d.ts 文件中排除声明。