从Node中启动TypeScript TSC编译器

3

我可以通过命令行来这样启动tsc编译器:

../../node_modules/.bin/tsc

我希望将此代码整合到一个Node.js构建脚本中。
虽然Node.js有TypeScript编译器,但似乎需要更多的工作来设置,而不是直接使用shell命令。你需要拉取所有正确的文件等。
这是我的代码:
fs.emptyDirSync(paths.appBuild);

const json = ts.parseConfigFileTextToJson(tsconfig, ts.sys.readFile(tsconfig), true);

const { options } = ts.parseJsonConfigFileContent(json.config, ts.sys, path.dirname(tsconfig));

options.configFilePath = paths.tsConfig;

options.outDir = outDir;
options.src = src;
options.noEmitOnError = true;
options.pretty = true;
options.sourceMap = process.argv.includes('--source-map');

let rootFile = path.join(process.cwd(), 'src/index.tsx');

if (!fs.existsSync(rootFile)) {
   rootFile = path.join(process.cwd(), 'src/index.ts');
}

const host = ts.createCompilerHost(options, true);
const prog = ts.createProgram([rootFile], options, host);
const result = prog.emit();

但这会漏掉在 RootFile 中未被导入的文件。

我该如何从 Node.js 简单地调用 tsc 可执行文件?

1个回答

2
你可以使用 child_process.exec
const path = require('path');
const { exec } = require('child_process');

const tscPath = path.join(__dirname, '../../node_modules/.bin/tsc');
const tsc = exec(`${tscPath} ${process.argv.slice(2).join(' ')}`);

tsc.stdout.on('data', data => console.log(data));
tsc.stderr.on('data', data => console.error(data));

tsc.on('close', code => console.log(`tsc exited with code ${code}`));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接