Vm2: Support TypeScript.

Created on 12 Oct 2020  ·  5Comments  ·  Source: patriksimek/vm2

Hi there, any plans to support typescript?
Or maybe there is someone who uses the custom ts compiler in production, if so would you like to share?

stale

Most helpful comment

Have you tried using the TypeScript Compiler API? It provides methods to transform TypeScript code into JavaScript code dynamically. I've used it before and it works great.

const {VM} = require('vm2');
const ts = require('typescript');

const vm = new VM();

const res = ts.transpile(`
    let x: number = 3;
    x + 5;
`);

console.log(vm.run(res)); // 8

All 5 comments

I would definitely like to see this, as I was trying to make a discord bot that executes typescript code but I couldn't find another typescript execution library that supports sandboxing and this is probably the best out there.
EDIT: it seems like this library uses https://nodejs.org/api/vm.html behind the scenes, which doesn't seem to support typescript either.

Have you tried using the TypeScript Compiler API? It provides methods to transform TypeScript code into JavaScript code dynamically. I've used it before and it works great.

const {VM} = require('vm2');
const ts = require('typescript');

const vm = new VM();

const res = ts.transpile(`
    let x: number = 3;
    x + 5;
`);

console.log(vm.run(res)); // 8

Oh, for some reason I didn't think of using it in combination with vm2 lol. I will try this, thanks.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

It should also be possible to set ts.transpile as compiler.
```JS
const {VM} = require('vm2');
const ts = require('typescript');

const vm = new VM({compiler: ts.transpile});

console.log(vm.run( let x: number = 3; x + 5; )); // 8

Was this page helpful?
0 / 5 - 0 ratings