Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render typescript file to javascript programmatically?

I'm trying to figure out how to render a typescript file programmatically to javascript file.

Is this possible to do with ts-node for example like this:

function tsMiddleware (req, res, next) {
    var parsed = require('url').parse(req.url);

    if (parsed.pathname.match(/\.ts$/)) {
        return ts(parsed.pathname).then(function (o) {
            res.setHeader('Content-Type', 'text/js');
            res.end(o.js);
        }).catch((err) => {
            console.log(err);
        });
    }
    next();

    function ts(src) {
        return new Promise((resolve, reject) => {
            require('ts-node').render({
                file: 'src' + src
            }, function (err, res) {
                if (err) {
                    reject(err);
                } else {
                    resolve(res);
                }
            });
        });
    }
}

I don't want to execute the ts file in nodejs, but instead just compile ts file and send the output back to the browser.

like image 344
user3141759 Avatar asked Jan 27 '26 15:01

user3141759


1 Answers

Here is an example:

const ts = require("typescript")
async function tsTranspile(tsCode) {
    return await ts.transpileModule(tsCode, { /* Here the compiler options */ })
}

How to use it:

tsTranspile("const f = a => a + 1")
    .then(jsCode => console.log(jsCode))
    .catch(err => console.log("Error:", err))

Read also:

  • Using the Compiler API;
  • Compiler Options.
like image 127
Paleo Avatar answered Jan 29 '26 04:01

Paleo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!