prettierはjavascript等のコード整形ツール(コードフォーマッター)で近年広く使用されている。公式のデモはここで試せる。通常はnode.jsで使用するが、ace editorで使用したいのでブラウザでの使用方法の備忘録。
コード
javascriptを整形する場合はパーサー一覧の中からbabelを使用する。babelはパーサープラグインとしてCDNから読み込む。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Browser Prettier</title>
<meta charset="utf-8">
</head>
<body>
<script src="https://unpkg.com/prettier@2.0.5/standalone.js"></script>
<script src="https://unpkg.com/prettier@2.0.5/parser-babel.js"></script>
<script>
const TestCode = `
//test code
const testa= "aaa"
const testb = "bbb"
const testc = "cccc"
`;
const result = prettier.format(TestCode, {
parser: "babel",
plugins: prettierPlugins,
});
console.log(result);
/*
//test code
const testa = "aaa";
const testb = "bbb";
const testc = "cccc";
*/
</script>
</body>
</html>