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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With