繁体   English   中英

如何使用带有expres和monaco-editor的Template文字

[英]How to work with Template literals with expres and monaco-editor

我正在尝试使用monaco编辑器通过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)
      });

我曾考虑过使用regexp代替Template Literal,但是我认为这不是最好的方法。 这是行不通的示例:

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错误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 })
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM