简体   繁体   中英

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

I'm trying to use monaco-editor to edit source code using web panel.

It is working just fine until I load a file that uses Template Literals.

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

I thought about using regexp to replace the Template Literal but I don't think it's the best possible way. this is not working example:

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') })
});

Error from browser: Uncaught SyntaxError: Unexpected identifier 浏览器突出显示错误

I've found a sollution it is the JSON.stringify.
.pug file :

...
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 })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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