基于 JavaScript 编写的 JavaScript 解释器;A JavaScript interpreter, written completely in JavaScript;
解决在不支持
eval
或Function
的执行环境下执行 JavaScript 代码。例如:微信小程序 示例。
npm install --save eval5
import { evaluate, Function, vm, Interpreter } from "eval5";
// 设置默认作用域
Interpreter.global = window;
//或 evaluate("1+1", Object.create(window));
evaluate("1+1", window); // 2
const func = new Function("a", "b", "return a+b;");
console.log(func(1, 1)); // 2
const interpreter = new Interpreter(ctx, {
timeout: 1000,
});
let result;
try {
result = interpreter.evaluate("1+1");
console.log(result); //2
} catch (e) {
//..
}
VERSION
object
默认:Object.create(null)
设置默认作用域对象
例如:
Interpreter.global = window;
readonly
替代原有的eval
占位符
如果执行环境支持 eval 函数建议使用原生的 eval,除非 eval 需要使用局部变量时,如下情况:
const ctx = Object.create(window);
ctx.eval = Interpreter.eval;
const interpreter = new Interpreter(ctx);
interpreter.evaluate(`
function test(){
var a = 1;
return eval('a+1')
}
test();
`); // output 2
readonly
替代原有的Function
占位符
作用同Interpreter.eval
除非不支持
Function
的环境,否则不建议使用
可选值: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
默认: 5
注:eval5 只支持 es5 语法,如果将 ecmaVersion 设为高版本尽管能编译通过,但解释时可能会报错或得到错误结果。
例如,如果设ecmaVersion=6
或更高,以下代码可以正常解析执行,但结果非预期:
const a = [];
for(let i = 0; i < 10; i++) {
a.push(function(){
console.log(i);
})
}
...
// output: 10 10 10...
原因在于解释器会忽略const
let
类型,都当作var
处理。
构造函数
var interpreter = new Interpreter(window);
返回脚本中执行的最后一个表达式结果
var interpreter = new Interpreter(window);
interpreter.evaluate("alert(1+1)");
作用同evaluate
单位:ms
获取evaluate
的执行时间
执行给定的字符串脚本,返回脚本中执行的最后一个表达式结果
evaluate("console.log(1+1)", { console: console });
同 js 原生的 Function
const func = new Function("a", "b", "return a+b;");
console.log(func(1, 2));
参考 node.js vm
支持 api 列表:
- vm.createContext
- vm.compileFunction
- vm.runInContext
- vm.runInNewContext
- vm.Script
MIT
- ECMA5