Skip to main content

How to format code in browser

· One min read
Jianhua Zheng
Jianhua Zheng
Frontend Engineer

There are times where we get codes by computation and would like to format them before displaying on the page.

prettier

Prettier comes with cli support which can be used on node environment. However, using prettier to format code on browser is possible. More detail can be found here. E.g.

import prettier from "https://unpkg.com/prettier@2.5.1/esm/standalone.mjs";
import parserBabel from "https://unpkg.com/prettier@2.5.1/esm/parser-babel.mjs";
import parserHtml from "https://unpkg.com/prettier@2.5.1/esm/parser-html.mjs";

console.log(
prettier.format("const html=/* HTML */ `<DIV> </DIV>`", {
parser: "babel",
plugins: [parserBabel, parserHtml],
})
);
// Output: const html = /* HTML */ `<div></div>`;

Sandbox example

js-beautify

import { js_beautify } from "js-beautify";
const rawJsCode = `
function add(a) {
return function(b){
return a + b;
}
}

sum(3)(5)
`;

js_beautify(rawJsCode);

/* Output:
* function add(a) {
* return function(b) {
* return a + b;
* }
* }
*
* sum(3)(5)