通过ES6实现个模板操作
const vm = require('vm'); const user = { name: '<script>xss</script>' } // 中控 const templateMap = { templateA: '`<p>${include("templateB")}</p>`', templateB: '`<div>templateB</div>`' } const context = { user, _: (v) => { var entry = { "'": "'", '"': '"', '<': '<', '>': '>' }; v = v.replace(/(['")-><&\\\/\.])/g, function ($0) { return entry[$0] || $0; }); return v; }, include: (name)=>{ return templateMap[name]() } } Object.keys(templateMap).forEach(key => { const temp = templateMap[key] templateMap[key] = vm.runInNewContext(` (function(){ return ${temp} }) `,context) }) // let str = `<h2>${user.name}</h2>`; // 把str 看作 eval(str)。需要有括号 const result = vm.runInNewContext("`<h2>${_(user.name)}</h2><h4>${include('templateA')}</h4>`", context); console.log('result is:', result) // result is: <h2><script>xss</script></h2><h4><p><div>templateB</div></p></h4>