先了解下情况

如果tsconfig.json中,同时配置了如下操作:

{
  "compilerOptions": {
    "charset": "utf8",
    "sourceMap": true,
    "allowSyntheticDefaultImports": true,
    "target": "es5",
    "moduleResolution": "node",
    "module": "umd",
    "outDir": "./dist",
    "experimentalDecorators": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "diagnostics": true,
    "allowJs": true,// 允许编译javascript文件
    "declaration": true,//生成相应的 .d.ts文件(类似Objc中的.h文件)
    "declarationDir": "./@types"//单独为头文件指定存放的位置
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

从这里开始,allowJs如果为true,则declaration就不应该存在。否则你将会看到编译时如下的报错…

Option ‘allowJs’ cannot be specified with option ‘declaration’.

看目录,好像需要的也都生成了!

但是作为一个优秀发程序员,能眼睁睁看到编译报错而不管嘛,当然不能!!!于是去撸github,发现早在2016年,微软那边就知道这事:issues-7546,但为毛现在还存在这个问题….

于是看他们讨论互怼,无意中看到巴基斯坦一兄弟的姿势。果断试了下,哎,别说,行了….

我把上边的操作整理了下,变成了一把梭,请看

"scripts": {
    "tsc": "tsc",
    "types": "tsc -d --emitDeclarationOnly --allowJs false --declarationDir ./@types",
    "prepublish": "npm run tsc && npm run types"
},

于是,之后你需要执行npm run prepublish就可以了。前提是把下边这两句从tsconfig.json中干掉

{
    "declaration": true,
    "declarationDir": "./@types"
}

如果读者有更成熟的方案,麻烦告知。感谢!