使用prettier插件时,报错:Error formatting code_ ConfigError_ Couldn‘t find plugin for AST format “estree“

291 阅读1分钟

同学们可以私信我加入学习群!


一、问题描述

纯前端使用prettier插件时,报错:Error formatting code: ConfigError: Couldn't find plugin for AST format "estree". Plugins must be explicitly added to the standalone bundle.

意思是找不到estree插件。

二、原因

注意是纯前端,nodejs、electron还没有尝试,不作为参考。

很有可能是你在纯前端代码中,使用import prettier from "prettier"引入插件,这样插件会去找默认解析器,博主介绍prettier和monaco使用的文章中提到过,前端使用插件,没有默认解析器。

如果直接引入prettier,不管如何设置parser属性,都无效,都会去找estree插件,所以会报找不到对应语言插件的错误。

三、解决方案

引入插件使用standalone或者prettier都可以,即:

import prettier from 'prettier/standalone'
或者
import prettier from 'prettier'

然后引入需要的插件:

import prettierPluginBabel from 'prettier/plugins/babel'
import prettierPluginVue from 'prettier/plugins/html'

在prettier中定义插件:

 const formatted = await prettier.format(jsonSource.value, {
      parser: 'json',
      plugins: [prettierPluginBabel, prettierPluginVue],// 根据需要添加
      semi: true,
      trailingComma: 'all',
      singleQuote: true,
      printWidth: 80,
      tabWidth: 2,
    })

总结

获取资源,查看代码示例,或者联系我:

lizetoolbox.top:8080/#/qrCode_co…