If you find this useful, please consider supporting my work with a donation.
A pluggable JavaScript source code formatter.
Prototype - Seeking feedback and not ready for production use.
By default, Nitpik JavaScript automatically makes the following changes:
Install using [npm][npm] or [yarn][yarn]:
npm install @nitpik/javascript --save
# or
yarn add @nitpik/javascript
Import into your Node.js project:
// CommonJS
const { JavaScriptFormatter } = require("@nitpik/javascript");
// ESM
import { JavaScriptFormatter } from "@nitpik/javascript";
Import into your Deno project:
import { JavaScriptFormatter } from "https://unpkg.com/@nitpik/javascript/dist/pkg.js";
Import into a browser script:
import { JavaScriptFormatter } from "https://unpkg.com/@nitpik/javascript/dist/pkg.js";
After importing, create a new instance of JavaScriptFormatter. The constructor accepts one argument which is a configuration object with the following keys:
true)true)4)"unix")1)Infinity)"double")true)4)false)true)For example:
const formatter = new JavaScriptFormatter({
style: {
indent: "\t",
quotes: "single"
}
});
const result = formatter.format(yourJavaScriptCode);
A plugin is a function that accepts one parameter, context, and returns an object specifying the types of nodes to visit in a JavaScript abstract syntax tree (AST). Here's an example that ensures there's an empty line before each function declaration:
function emptyLineBeforeFunctions(context) {
const { layout } = context;
return {
FunctionDeclaration(node) {
layout.emptyLineBefore(node);
}
};
}
This function uses the context.layout property to specify that there should be an empty line before each function declaration node. FunctionDeclaration is the type of node to look for, as defined by ESTree. The node is passed as an argument to each method as the AST is traversed, so in this example, node represents a function declaration. You can then include the function in the plugins array of the configuration options:
const formatter = new JavaScriptFormatter({
style: {
indent: "\t",
quotes: "single"
},
plugins: [
emptyLineBeforeFunctions
]
});
const result = formatter.format(yourJavaScriptCode);
When the formatter is run, it will now run any specified plugins after a first-pass of formatting based on the style options. This makes it easy to define a default style and then modify it to suit your needs.
All of the style options are implemented internally as plugins. Please see the src/plugins directory for examples (documentation to come later).
npm installnpm test to run testsThis code is licensed under the Apache 2.0 License (see LICENSE for details).
Copyright Human Who Codes LLC. All rights reserved.