有没有办法为生成的 .d.ts 文件(在 JavaScript 项目中)声明特定的模块名称?

And*_*ing 5 javascript typescript tsconfig .d.ts

有没有办法为生成的.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/**/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

And*_*ing 4

不幸的是,类型不能直接输出到单个文件。有一个公开提案添加“类型捆绑”(#4433)来添加该功能。还有第三方库可以帮助解决这个问题。

如果您同意输出多个文件,另一种解决方案是指定outDir而不是outFile. 这是我选择的解决方案,设置"outDir": "./types"intsconfig.json并设置"types": "./types/index.d.ts"in package.json。将模块导入其他项目时,这正如我预期的那样。