如何为tsconfig.json使用CommonJS文件?

时间:2020-04-20 02:10:06

标签: typescript tsconfig

许多系统(Mocha,ESLint,NYC)为您提供希望配置文件采用哪种格式的选项(commonjs / js,json,yml等)。

这很有用,因为在CommonJS中(使用module.exports,您可以在配置文件中添加注释,或者在配置文件中包含其他代码,这提供了很大的灵活性。

有没有办法在TypeScript中做到这一点,并使用CommonJS或module.exports来定义tsconfig文件,而不是仅使用json文件?

1 个答案:

答案 0 :(得分:-1)

我将tsconfig.json保留为json,并在README.md中添加必要的注释。

其他选项是像这样在json中添加注释:

// tsconfig.json
{
  "//comment": "comment content",
  "compilerOptions": {
    ...
  },
}

如果需要更大的灵活性,则可以添加一个构建步骤,以从.js文件生成tsconfig.json

// tsconfig.js
// comments or code here

module.exports = {
  "compilerOptions": {
    "module": "commonjs",
  },
};
// tsconfigBuilder.js

const fs = require('fs');
const config = require('./tsconfig');

fs.writeFileSync('./tsconfig.json', JSON.stringify(config, null, 2));

package.json中添加脚本,以在编译器步骤之前从tsconfig.json生成tsconfig.js

// package.json

  "scripts": {
    "build-tsconfig": "node tsconfigBuilder.js",
    ...
  },

您完成了。

相关问题