【发布时间】:2022-09-27 14:57:00
【问题描述】:
我需要能够格式化各种语言的代码。为此,我使用了 3 个不同的 HTML、CSS 和 JS 库,它们都非常大。
为了减少不必要的代码,我想使用我已经在使用的 monaco 库中的现有代码格式化程序来创建这样的函数:
function getFormattedCode(code, mimeType/fileExtension) { ... }
到目前为止,由于这里可以看到许多问题,我一直无法有效地做到这一点:
const editor = monaco.editor.create(document.getElementById(\"container\"));
function format(code, fileName) {
return new Promise(resolve => {
const model = monaco.editor.createModel(
code,
undefined,
monaco.Uri.file(fileName),
);
editor.setModel(model);
setTimeout(() => {
editor.getAction(\"editor.action.formatDocument\").run();
setTimeout(() => resolve(model.getValue()), 500);
}, 100);
});
}
!async function () {
alert(await format(\"x=1\", \".js\"));
}();
需要长时间的延迟,并且编辑器的实际 HTML 正在被不必要地修改。
有没有办法从 monaco 库中提取格式化功能?