首页 > 解决方案 > 有没有办法为生成的 .d.ts 文件(在 javascript 项目中)声明特定的模块名称?

问题描述

有没有办法为生成的.d.ts文件声明不同的模块名称?

tsc 生成declare module "index" {而不是declare module "@myorg/my-pkg"(这将匹配 中的name属性package.json)。

注意:这是在我试图生成类型的纯 javascript 项目中。

/* Generated with tsc --init via TypeScript 3.7.0-beta */
{
  "compilerOptions": {
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
     "allowJs": true,                         /* Allow javascript files to be compiled. */
     "declaration": true,                     /* Generates corresponding '.d.ts' file. */
    "outFile": "./lib/index.js",              /* Concatenate and emit output to single file. */
    "emitDeclarationOnly": true,              /* Only emit .d.ts files. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": [
    "js/**/*"
  ]
}

标签: javascripttypescripttsconfig.d.ts

解决方案


不幸的是,类型不能输出到开箱即用的单个文件中。有一个开放的提议来添加“类型捆绑”(#4433)来添加该功能。还有 3rd 方库可以帮助解决这个问题。

另一种解决方案,如果您可以输出多个文件,则可以指定outDir而不是outFile. 这是我选择的解决方案,"outDir": "./types"设置和tsconfig.json设置"types": "./types/index.d.ts"package.json将模块导入其他项目时,这符合我的预期。


推荐阅读