I have code editor (CodeMirror v6) inside my ReactJS app and want to format code post edit with prettier. How to run prettier in browser?
Looking for something like:
prettier.format(code)
That's what found out after some test and fails:
There is Standalone package of prettier which does not require anything from NodeJs.
It has some limitations:
It only formats the code and has no support for config files, ignore files, CLI usage, or automatic loading of plugins. https://prettier.io/docs/en/browser.html
Also inside prettier.format
selected plugins and parser must be set manually.
Inside index.html, add standalone prettier + babel parser, which is enough to run prettier from a global variable:
// 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>
prettierPlugins
was also exposed from these script tags, it is not my custom code.