how to compile typescript to javascript code example
Example 1: how to run typescript file
npx ts-node src/foo.ts
Example 2: typescript compile string to js
import * as ts from "typescript";
function tsCompile(source: string, options: ts.TranspileOptions = null): string {
if (null === options) {
options = { compilerOptions: { module: ts.ModuleKind.CommonJS }};
}
return ts.transpileModule(source, options).outputText;
}
const source = "let foo: string = 'bar'";
let result = tsCompile(source);
console.log(result);
Example 3: how to compile ts in cmd
"scripts": {
"clean": "rimraf dist",
"start": "npm-run-all clean --parallel watch:build watch:server --print-label",
"watch:build": "tsc --watch",
"watch:server": "nodemon './dist/index.js' --watch './dist'"
}