javascript 使用monaco编辑器无法以更漂亮的格式工作

myzjeezk  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(336)

我正在尝试使用Monaco编辑器制作一个在浏览器中工作的IDE。我想使用Prettier来获得一个不错的格式。它只适用于Javascript文件或html文件。但是,它不适用于我下面指定的类型的文件。我该如何修复呢?
预期值:

结果:

此外,我得到这个错误:

monaco.languages.registerDocumentFormattingEditProvider("javascript", {
            async provideDocumentFormattingEdits(model) {
                alert(1);
                var text1 = prettier.format(model.getValue(), {
                    wrapAttributes: "force",
                    parser: "babel",
                    // plugins: [babel],
                    htmlWhitespaceSensitivity: "ignore",
                    arrowParens: "always",
                    bracketSpacing: true,
                    endOfLine: "lf",
                    insertPragma: false,
                    singleAttributePerLine: false,
                    bracketSameLine: false,
                    printWidth: 400,
                    proseWrap: "preserve",
                    quoteProps: "as-needed",
                    requirePragma: false,
                    semi: true,
                    singleQuote: true,
                    tabWidth: 4,
                    //trailingComma: 'es5',
                    useTabs: false,
                    vueIndentScriptAndStyle: false,
                });

               

                return [
                    {
                        range: model.getFullModelRange(),
                        text: text1,
                    },
                ];
            },
        });
 monaco_scr_editor = monaco.editor.create(document.getElementById("browserIDE"), {
            value: ["<html>Please Wait Loading</html>"].join("\n"),
            language: "javascript",
            theme: "vs-dark",
            wrappingColumn: 0,
            autoIndent: true,
            formatOnPaste: true,
            formatOnType: true,
            wrappingIndent: "indent",
            wordWrap: "off",
            automaticLayout: true,
            overviewRulerLanes: 1,
            overviewRulerBorder: true,
            minimap: { enabled: false },
        });
kqhtkvqz

kqhtkvqz1#

您需要为options.parser提供正确的值。
来自文档
options.parser必须根据您正在格式化的语言来设置(请参阅可用解析器列表)。或者,可以为Prettier指定options.filepath,以便从文件扩展名推断解析器。
因此将其设置为parser: "html"

zyfwsgd6

zyfwsgd62#

它看起来像设计使用预定义的格式化程序。
请参考此问题:Disable default formatters。我测试了如下代码(来自线程),

monaco.languages.html.htmlDefaults.setModeConfiguration({
   ...monaco.languages.html.htmlDefaults.modeConfiguration,
   documentFormattingEdits: false,
   documentRangeFormattingEdits: false,
});

这对你有用。
但你还是会把漂亮和错误联系起来。
参考此问题:https://github.com/prettier/prettier/issues/6264
在执行此操作之前,安装此命令,以便从node_module轻松导入解析器列表。

npm install @types/prettier

然后将其导入。

import * as prettier from  'prettier/standalone'
import * as parserHtml from 'prettier/parser-html'
...
prettier.format(model.getValue(), {
                ...
                parser: "html",
                plugins: [parserHtml],
                ...

相关问题