Skip to content

Instantly share code, notes, and snippets.

@zlataovce
Created July 2, 2026 13:01
Show Gist options
  • Select an option

  • Save zlataovce/651f873d0568dbd9442feeb84dc7b922 to your computer and use it in GitHub Desktop.

Select an option

Save zlataovce/651f873d0568dbd9442feeb84dc7b922 to your computer and use it in GitHub Desktop.
A slicer script for formatting JS and JSON.
import "https://cdn.jsdelivr.net/npm/js-beautify@2.0.3/js/lib/beautify.js";
const indentSizeOption = {
type: "radio",
id: "js-formatter/indent-size",
label: "Indent size",
items: [
{
id: "2",
label: "2 spaces",
},
{
id: "4",
label: "4 spaces",
},
{
id: "8",
label: "8 spaces",
},
],
selected: "4",
};
const EXTENSIONS = ["js", "cjs", "mjs", "json", "jsonc", "json5"];
const utf8Decoder = new TextDecoder();
const utf8Encoder = new TextEncoder();
export default {
name: "JS formatter",
description: "Formats JS (and JSON) using the js-beautify library.",
version: "1.0.0",
options: [indentSizeOption],
load(context) {
context.addEventListener("transform", (e) => {
if (EXTENSIONS.some((ext) => e.name.endsWith(`.${ext}`))) {
const data = utf8Decoder.decode(e.data);
const formatted = js_beautify(data, {
brace_style: "expand",
indent_size: parseInt(indentSizeOption.selected, 10),
});
e.data = utf8Encoder.encode(formatted);
}
});
},
unload() {},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment