如何在浏览器中运行 prettier 来格式化代码?例如ReactJs 应用程序内部

2023-11-29

我的 ReactJS 应用程序中有代码编辑器(CodeMirror v6),并且希望使用 Prettier 格式化代码后期编辑。如何在浏览器中运行得更漂亮?

寻找类似的东西:

prettier.format(code)


这是经过一些测试并失败后发现的:

Prettier 有一个独立的包,它不需要 NodeJs 的任何东西。

它有一些限制:

它仅格式化代码,不支持配置文件、忽略文件、CLI 使用或自动加载插件。https://prettier.io/docs/en/browser.html

也在里面prettier.format所选插件和解析器必须手动设置。

在index.html中,添加独立的prettier + babel解析器,这足以从全局变量运行prettier:

// JS script, should be run after <script> tags load
const formatted = prettier.format("console.log( 'ok')", {
  parser: "babel",
  plugins: prettierPlugins,
});
console.log(formatted);
<!-- HTML -->
<script src="https://unpkg.com/[email protected]/standalone.js"></script>
<script src="https://unpkg.com/[email protected]/parser-babel.js"></script>

enter image description here

prettierPlugins也从这些脚本标签中暴露出来,它不是我的自定义代码。

enter image description here enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在浏览器中运行 prettier 来格式化代码?例如ReactJs 应用程序内部 的相关文章

随机推荐