dagda1
dagda1

Reputation: 28930

start typescript tsc compiler from node

From the command line I can start the tsc compiler like this:

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

I want to incorporate this into a node build script.

There is a typescript compiler for node but it seems much more work to set up rather than just shelling out. You have to pull in all the right files etc.

I have this code :

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();

But This will miss files that are not imported in the RootFile.

How can I simply shell out to the tsc exe from node?

Upvotes: 3

Views: 569

Answers (1)

Phil Booth
Phil Booth

Reputation: 4907

You could use 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}`));

Upvotes: 2

Related Questions