eval5是基于TypeScript编写的JavaScript解释器,100%支持ES5语法。
项目地址:https://github.com/bplok20010/eval5
使用场景
- 浏览器环境中需要使用沙盒环境执行JavaScript脚本
- 控制代码执行时长
- 不支持
eval
Function
的JavaScript运行环境:如 微信小程序 - 研究/学习用
安装
npm install --save eval5
使用
import { Interpreter } from 'eval5';
const ctx = {
console,
hello(){
console.log('hello eval5')
}
}
var interpreter = new Interpreter(ctx, {
timeout: 1000
});
var result = interpreter.evaluate(`
hello();
function sum(a, b) {
return a + b;
}
sum(100,2 00);
`)
console.log(result); // 300
eval5不支持es6语法,可以先将es6或typescript转成es5