12

Is there a way to compile a String containing TypeScript to its JavaScript String equivalent ?

For instance, in Coffeescript (and LiveScript, coco etc) its a (simplified) one-liner:

jsCompiledCode = require('coffee-script').compile('do -> console.log "Hello world"', {bare:true});

Can something similar be implemented for TypeScript, preferably without involving the filesystem ? Are there any implications with referencing other modules that would have to be resolved at compile time ?

2 Answers 2

21

You can use the transpileModule() method that comes with TypeScript.

$ npm install typescript
// compile.ts

import * as ts from "typescript";

function tsCompile(source: string, options: ts.TranspileOptions = null): string {
    // Default options -- you could also perform a merge, or use the project tsconfig.json
    if (null === options) {
        options = { compilerOptions: { module: ts.ModuleKind.CommonJS }};
    }
    return ts.transpileModule(source, options).outputText;
}

// Make sure it works
const source = "let foo: string  = 'bar'";

let result = tsCompile(source);

console.log(result); // var foo = 'bar';

When compiling this you will need the tsconfig moduleResolution set to "Node".

This will compile / execute the above example file.

$ tsc compile.ts --moduleResolution Node && node compile.js

There is also some documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

How will this handle import x from './relative/path' and such, is there a way to specify how its imports work?
@Lance You may want to reach for something other than this method if you want to bundle or check types across files. As for how it handles imports that will entirely depend on the options you pass in. For instance, the default in the method now is to use CommonJS, so imports will be transformed into require() calls. Note: the imported module would neither be bundled nor compiled by default.
5

You can use TypeScript.Api nodejs package : https://npmjs.org/package/typescript.api

In particular check out this function : https://github.com/sinclairzx81/typescript.api#compile

1 Comment

I was hoping for a no-3rd-party-package solution, to easily use for urequire Resource Converters (urequire.org/resourceconverters.coffee). I see that TypeScript is very opinionated about its modules... There's quite a bit of work to support cross nodejs/AMD/typescript in uRequire I guess...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.