jshiki provides a safe and easy way to evaluate expressions without worrying about external data being overwritten or accessed in unexpected ways. jshiki only has one lightweight dependency, acorn, which it uses to parse expressions.
IMPORTANT! jshiki is not a true sandbox. If you need to be able to evaluate arbitrary code of unknown origin, you may want to consider using vm2 or a similar library.
const jshiki = require('jshiki')
let result = jshiki.evaluate('(5 + 7) / 3') // result => 4
// or
let expression = jshiki.parse('(5 + 7) / 3')
result = expression() // result => 4
const code = "`Hello! My name's ${name.trim()}`"
expression = jshiki.parse(code)
result = expression({ name: ' Azumi ' })
// result => "Hello! My name's Azumi"
// or
result = jshiki.evaluate(code, {
scope: { name: ' Azumi ' },
})
// result => "Hello! My name's Azumi"
const asyncCode = "`I'm ${await status()}...`"
expression = jshiki.parseAsync(asyncCode)
result = await expression({
status: async () => 'waiting',
})
// result => "I'm waiting..."
// or
result = await jshiki.evaluateAsync(asyncCode, {
scope: { status: async () => 'waiting' },
})
// result => "I'm waiting..."
For more examples, features, and information on how to use jshiki, see the documentation.
Discuss jshiki on GitHub discussions. Make sure to follow the code of conduct.
If you're looking for a way to contribute to jshiki, see the contribution guide.