如何在 express 和 monaco-editor 中使用模板文字

How to work with Template literals with expres and monaco-editor

我正在尝试使用 monaco-editor 通过 Web 面板编辑源代码。

在我加载使用模板文字的文件之前,它工作正常。

index.js:

function processFile(inputFile) {
    let fs = require('fs'),
        path = require('path'),
        rl = fs.readFileSync(path.join(__dirname,'../','../','../','apps/',inputFile));
    return rl.toString('utf8');
}
router.get('/', function (req, res) {
    res.render('index', { title: 'Hey', message: 'Hello there!', test: processFile('libs/ButtonTest.js') })
});

index.pug:

doctype html
html
  head
    title= title
    script(src='monaco/vs/loader.js')
  body
    h1= message
    div(id='container', style='width: 800px;height: 800px;')
    script.
      require.config({paths: {"vs": "monaco/vs"}});
      require(["vs/editor/editor.main"], function() {
        var model = monaco.editor.createModel(`!{test}`,'javascript');
        var editor = monaco.editor.create(document.getElementById("container"));
        editor.setModel(model)
      });

我考虑过使用正则表达式来替换模板文字,但我认为这不是最好的方法。 这不是工作示例:

var test = [];
test.push("var t = 'test t';");
test.push('var c = "test c";');
test.push('var o = `test o ${c}, ${t}`;');
router.get('/', function (req, res) {
    res.render('index', { title: 'Hey', message: 'Hello there!', test: test.join('\r\n') })
});

浏览器错误:Uncaught SyntaxError: Unexpected identifier

我找到了一个解决方案,它是 JSON.stringify。
.pug 文件:

...
var d = !{test};
var model = monaco.editor.createModel(d.join('\r\n'),'javascript');
...

index.js

var test = [];
test.push("var t = 'test t';");
test.push('var c = "test c";');
test.push('var o = `test o ${c}, ${t}`;');
let c = JSON.stringify(test);

router.get('/', function (req, res) {
    res.render('index', { title: 'Hey', message: 'Hello there!', test: c })
});