GitPedia

Putout

🐊 Pluggable and configurable JavaScript Linter, code transformer and formatter with superpowers πŸ’ͺ: built-in support of js, jsx, ts, markdown, yaml, toml, json and ignore. Write declarative codemods in a simplest possible way 😏

From coderaiserΒ·Updated June 19, 2026Β·View on GitHubΒ·

[NPMURL]: https://npmjs.org/package/putout "npm" [NPMIMGURL]: https://img.shields.io/npm/v/putout.svg?style=flat&longCache=true [BuildStatusURL]: https://github.com/coderaiser/putout/actions?query=workflow%3A%22Node+CI%22 "Build Status" [BuildStatusIMGURL]: https://github.com/coderaiser/putout/workflows/Node%20CI/badge.svg [CoverageURL]: https://coveralls.io/github/coderaiser/putout?branch=master [CoverageIMGURL]: https://coveralls.io/repos/coderaiser/putout/badge.svg?branch=master&service=githu... The project is written primarily in JavaScript, distributed under the MIT License license, first published in 2018. Key topics include: ast, babel, babel-plugin, codemod, codemods.

Latest release: v42.7.3β€” putout v42.7.3

Putout NPM version Build Status Coverage Status DeepScan

Perfection is finally attained not when there is no longer anything to add,
but when there is no longer anything to take away.

(c) Antoine de Saint ExupΓ©ry

putout

🐊Putout is a JavaScript Linter, pluggable and configurable code transformer, drop-in ESLint replacement with built-in code printer and ability to fix syntax errors. It has lots of transformations that keeps your codebase in a clean state, removing any code smell and making code readable according to best practices.

The main target is JavaScript, but:

  • βœ… JSX;
  • βœ… TypeScript;
  • βœ… Yaml;
  • βœ… TOML;
  • βœ… Markdown;
  • βœ… JSON;
  • βœ… Ignore;
  • βœ… Dockerfile;

are also supported. Here is how it looks like:

putout

Table of contents

πŸ€·β€β™‚οΈ In doubt about using 🐊Putout?

Check out couple variants of plugins that does the same: linting debugger statement:

js
export const report = () => `Avoid 'debugger' statement`; export const replace = () => ({ debugger: '', });

Choose wisely, competitors cannot even fix… 🀫

Drop-in ESLint replacement

🐊Putout in addition to own format .putout.json supports both eslint.config.js and .eslintrc.json, it has ability to autodect format you use.
Also it works good with monorepository, since it uses eslint.config.js that is closer to linting file, instead of cwd of ESLint run.

πŸ™ Whom should I thank for this project exist?

If I have seen further, it is by standing upon the shoulders of giants.

(c) Isaac Newton

  • πŸ’ͺESLint for stable releases and future proof API.
  • πŸ’ͺBabel for amazing API documented in Handbook and responsiveness of a team.
  • πŸ’ͺPrettier for minimalistic options and uniform codestyle.
  • πŸ’ͺJSCodeshift for making codemods simple and popular.

πŸ€·β€β™‚οΈ Why does this project exist?

🐊Putout on the other hand can make more drastic code transformations that directly affects your codebase making it a better place to code πŸ’»:

🚚 Installation

To install 🐊Putout as a development dependency, run:

npm i putout -D 

Make sure that you are running a relatively recent (β‰₯16) version of Node.

πŸŽ™ Usage

Grown-ups never understand anything by themselves, and it is tiresome for children to be always and forever explaining things to them.

(c) Antoine de Saint-ExupΓ©ry

🐊Putout tries to be clear and likes a lot to explain things. So when you write putout --help most likely you will hear gladly purr :

Usage: putout [options] [path]
Options:
   -h, --help                  display this help and exit
   -v, --version               output version information and exit
   -f, --format [formatter]    use a specific output format, the default is: 'progress-bar' locally and 'dump' on CI
   -s, --staged                add staged files when in git repository
   -i, --interactive           set lint options using interactive menu
   --fix                       apply fixes of errors to code
   --fix-count [count = 10]    count of fixes rounds
   --rulesdir                  use additional rules from directory
   --transform [replacer]      apply Replacer, for example 'var __a = __b -> const __a = __b', read about Replacer https://git.io/JqcMn
   --plugins [plugins]         a comma-separated list of plugins to use
   --enable [rule]             enable the rule and save it to '.putout.json' walking up parent directories
   --disable [rule]            disable the rule and save it to '.putout.json' walking up parent directories
   --enable-all                enable all found rules and save them to '.putout.json' walking up parent directories
   --disable-all               disable all found rules (set baseline) and save them to '.putout.json' walking up parent directories
   --match [pattern]           read '.putout.json' and convert 'rules' to 'match' according to 'pattern'
   --fresh                     generate a fresh cache
   --no-config                 avoid reading '.putout.json'
   --no-ci                     disable the CI detection
   --no-cache                  disable the cache
   --no-worker                 disable worker thread

To skip prefix node_modules/.bin/, update your $PATH variable in with .bashrc:

sh
echo 'PATH="$PATH:node_modules/.bin"' >> ~/.bashrc source ~/.bashrc

To find possible transform places in a folder named lib, run:

putout lib

To find possible transform places in multiple folders, such as folders named lib and test, run:

putout lib test

To apply the transforms, use --fix:

putout lib test --fix

☝️Commit your code before running 🐊Putout

Developers, myself included, usually prefer to make all code changes manually, so that nothing happens to our code without reviewing it first. That is until we trust a tool to make those changes safely for us. An example is WebStorm, which we trust when renaming a class or a method. Since 🐊Putout may still feel like a new tool, not all of us will be able to trust it immediately.

A good way to gain trust is two run without --fix option, and observe error messages. Another way is to use traditional version control tactics. Before running 🐊Putout you should do a git commit. Then after running 🐊Putout, you’ll be able to inspect the changes it made using git diff and git status. You still have the chance to run git checkout -- . at any time to revert all the changes that 🐊Putout has made. If you need more fine-grained control, you can also use git add -p or git add -i to interactively stage only the changes you want to keep.

Environment variables

🐊Putout supports the following environment variables:

  • PUTOUT_CONFIG_FILE - path to configuration file;
  • PUTOUT_FILES - files that should be processed split by comma (,);

Example:

PUTOUT_FILES=lib,test putout --fix

πŸ¦• Usage with Deno

When you need to run 🐊Putout in Deno, use @putout/bundle:

js
import putout from 'https://esm.sh/@putout/bundle'; import removeDebugger from 'https://esm.sh/@putout/plugin-remove-debugger?alias=putout:@putout/bundle'; import declare from 'https://esm.sh/@putout/plugin-declare?alias=putout:@putout/bundle'; putout('isFn(fn); debugger', { plugins: [ ['remove-debugger', removeDebugger], ['declare', declare], ], }); // returns ({ code: `const isFn = a => typeof a === 'function';\nisFn(fn);`, places: [], });

πŸ“ What is Ruler?

When you need to change configuration file use Ruler instead of editing the file manually.

Ruler can:

  • βœ… putout --enable [rule];
  • βœ… putout --disable [rule];
  • βœ… putout --enable-all;
  • βœ… putout --disable-all;

☝️Remember, Ruler should never be used with --fix, because unclear things makes 🐊 Putout angry and you can find him barking at you:

🐊 '--fix' cannot be used with ruler toggler ('--enable', '--disable')

βœ‚οΈ How Ruler can help me?

You may want to convert your CommonJS to ESM since node v12 supports it without a flag.

🚁 Convert CommonJS to ESM

☝️ I have a package.json

Well, if you have no type field or type=commonjs your package will be
converted to CommonJS automatically. To convert to ESM just set type=module.

☝️ I have .cjs or .mjs files

They will be converted automatically to CommonJS and ESM accordingly.

☝️ I want to run only one rule

Let's suppose you have a file called index.js:

js
const unused = 5; module.exports = function() { return promise(); }; async function promise(a) { return Promise.reject(Error('x')); }

You call putout --fix index.js and see that file is changed:

js
'use strict'; module.exports = async function() { return await promise(); }; async function promise() { throw Error('x'); }

But for some reason you don't want so many changes.

☝️ Remember, safe mode of eslint-plugin-putout has the most dangerous rules disabled, so it can be used as auto fix on each save in your IDE.

So, if you want to convert it to ESM keeping everything else untouched use Ruler: it can easily disable all rules 🐊Putout finds.

putout index.js --disable-all will find next errors:

sh
1:4 error 'unused' is defined but never used variables/remove-unused 7:23 error 'a' is defined but never used variables/remove-unused 3:0 error Use arrow function convert-to-arrow-function 1:0 error Add missing 'use strict' directive on top of CommonJS nodejs/add-missing-strict-mode 8:4 error Reject is useless in async functions, use throw instead promises/convert-reject-to-throw 4:11 error Async functions should be called using 'await' promises/add-missing-await 7:0 error Avoid useless async promises/remove-useless-async

It will create config file .putout.json:

json
{ "rules": { "variables/remove-unused": "off", "convert-to-arrow-function": "off", "nodejs/add-missing-strict-mode": "off", "promises/convert-reject-to-throw": "off", "promises/add-missing-await": "off", "promises/remove-useless-async": "off" } }

Then running putout index.js --enable nodejs/convert-commonjs-to-esm will update config with:

diff
{ "rules": { "variables/remove-unused": "off", "convert-to-arrow-function": "off", "nodejs/add-missing-strict-mode": "off", "promises/convert-reject-to-throw": "off", "promises/add-missing-await": "off", - "promises/remove-useless-async": "off" + "promises/remove-useless-async": "off", + "nodejs/convert-commonjs-to-esm": "on" } }

Then putout --fix index.js will do the thing and update index.js with:

js
const unused = 5; export default function() { return promise(); } async function promise(a) { return Promise.reject(Error('x')); }

So in case of src directory, it will look like:

sh
putout src --disable-all && putout src --enable nodejs/convert-commonjs-to-esm && putout src --fix

This command will disable all rules that 🐊Putout can find right now and enable a single rule. All built-in rules made for good and highly suggested to be used, all of them are enabled in all my repositories, since they have auto fix.

☝️You can always disable what you don't need, so give it a try. You won't regret 🐊.

Happy coding 🎈!

πŸ› Architecture

🐊Putout consists of a couple simple parts, here is a workflow representation:

putout

And here is a CLI scheme:

putout

🌲 The Tree of Syntax

**The wise speak of the perennial Ashvattha tree,
which has roots above and branches below.
The leaves protecting it are the Vedas.
One who knows this, truly knows.**The tender sprouts of this mighty tree
are the senses nourished by the gunas.
The branches extend both above and below.
The secondary roots going downward represent actions
that bind the individual soul to earthly existence.

(c) β€œBhagavatgita”, chapter 15

Ashvattha

On the bottom level of 🐊Putout layes down Syntax Tree. This is data structure that makes it possible to do crazy transformations in a simplest possible way. It is used mostly in compilers development.

You can read about it in Babel Plugin Handbook. To understand how things work from the inside take a look at Super Tiny Compiler.

Preoccupied with a single leaf, you won't see the tree.
Preoccupied with a single tree, you'll miss the entire forest.
When you look at a tree, see it for its leaves, its branches, its trunk and the roots, then and only then will you see the tree.

(c) Takuan Soho, "The Unfettered Mind: Writings of the Zen Master to the Sword Master"

Consider next piece of code:

js
hello = 'world';

It looks this way in ESTree JavaScript syntax format:

json
{ "type": "AssignmentExpression", "operator": "=", "left": { "type": "Identifier", "name": "hello" }, "right": { "type": "StringLiteral", "value": "world" } }

When one is not capable of true intelligence, it is good to consult with someone of good sense. An advisor will fulfill the Way when he makes a decision by selfless and frank intelligence because he is not personally involved. This way of doing things will certainly be seen by others as being strongly rooted. It is, for example, like a large tree with many roots.

(c) Yamamoto Tsunetomo "Hagakure"

🐊Putout based on Babel AST. It has a couple of differences from ESTree which are perfectly handled by estree-to-babel.

☝️ You can get more information about AST in The Book of AST.

🌴 Laws of the Jungle

  • πŸ… engines chilling with engines, and chasing plugins, processors, operators;
  • 🦌 plugins chilling with plugins and operators via require('putout').operator;
  • πŸ¦’ processors chilling with processors;
  • πŸƒ operators chilling with operators;

πŸ’š Engines

Engines is the heart of 🐊Putout: Parser, Loader and Runner are running for every processed file. Processor runs all the processors.

PackageVersion
@putout/engine-parsernpm
@putout/engine-loadernpm
@putout/engine-runnernpm
@putout/engine-processornpm
@putout/engine-reporternpm

πŸ§ͺ Processors

With help of processors 🐊Putout can be extended to read any file format and parse JavaScript from there.

Here is a list of built-in processors:

PackageVersion
@putout/processor-javascriptnpm
@putout/processor-jsonnpm
@putout/processor-markdownnpm
@putout/processor-ignorenpm
@putout/processor-yamlnpm
@putout/processor-tomlnpm
@putout/processor-dockernpm
@putout/processor-cssnpm
@putout/processor-filesystemnpm
@putout/processor-htmlnpm
You can disable any of them with:
json
{ "processors": [ ["markdown", "off"] ] }

Not bundled processors:

PackageVersion
@putout/processor-dockernpm
@putout/processor-typescriptnpm
@putout/processor-sveltenpm
@putout/processor-wasmnpm
External processors:
PackageVersion
putout-processor-typosnpm
To enable, install and use:
json
{ "processors": [ ["typescript", "on"] ] }

Processors can be tested using @putout/test/processors.

πŸ— API

In one’s life there are levels in the pursuit of study. In the lowest level, a person studies but nothing comes of it, and he feels that both he and others are unskillful. At this point he is worthless. In the middle level he is still useless but is aware of his own insufficiencies and can also see the insufficiencies of others. At a higher level, he has pride concerning his own ability, rejoices in praise from others, and laments the lack of ability in his fellows. This man has worth. At the highest level a man has the look of knowing nothing.

(c) Yamamoto Tsunetomo "Hagakure"

In the similar way works 🐊Putout API: it has no
plugins defined, tabula rasa.

putout(source, options)

First things first, require putout:

js
const putout = require('putout');

Let's consider the next source with two VariableDeclarations and one CallExpression:

js
const hello = 'world'; const hi = 'there'; console.log(hello);

We can declare it as source:

js
const source = ` const hello = 'world'; const hi = 'there'; console.log(hello); `;

Plugins

🐊Putout supports dynamic loading of plugins from node_modules. Let's consider example of using the variables/remove-unused plugin:

js
putout(source, { rules: { 'variables': 'off', 'variables/remove-unused': 'on', }, plugins: ['variables'], }); // returns ({ code: `\n const hello = 'world';\n\n console.log(hello);\n`, places: [], });

As you see, places is empty, but the code is changed: there is no hi variable.

No fix

From the beginning, 🐊Putout developed with ability to split the main process into two concepts: find (find places that could be fixed) and fix (apply the fixes to the files).
It is therefore easy to find sections that could be fixed.
In the following example redundant variables are found without making changes to the source file:

js
putout(source, { fix: false, rules: { 'variables': 'off', 'variables/remove-unused': 'on', }, plugins: ['variables'], }); // returns ({ code: '\n' + ` const hello = 'world';\n` + ` const hi = 'there';\n` + ' \n' + ' console.log(hello);\n', places: [{ rule: 'variables/remove-unused', message: '"hi" is defined but never used', position: { line: 3, column: 10, }, }], });

πŸ—Ί Source map

Source maps are embedded in the generated source using a special comment. These comments may contain the entire source map, using a Data URI, or may reference an external URL or file.

(c) Source maps in Node.js

In our case Data URL used. Here is an example of source map:

json
{ "version": 3, "file": "out.js", "sourceRoot": "", "sources": [ "foo.js", "bar.js" ], "names": [ "src", "maps", "are", "fun" ], "mappings": "AAgBC,SAAQ,CAAEA" }

To generate source map you can use:

js
const {generate} = require('@putout/engine-parser'); const {parse} = require('@putout/engine-parser/babel'); const ast = parse(source, { sourceFilename: 'hello.js', }); generate(ast, {sourceMaps: true}, { 'hello.js': source, }); // returns ({ code, map, });

🏨 Built-in transformations

JavaScript

<details><summary>remove <code>unused variables</code></summary>
diff
function show() { - const message = 'hello'; console.log('hello world'); }
</details> <details><summary>remove unused <code>for...of variables</code></summary>
diff
-for (const {a, b} of c) { +for (const {a} of c) { console.log(a); }
</details> <details><summary>remove <code>unreferenced variables</code></summary>
diff
-let a; - a = 1; let b; b = 2; console.log(b);
</details> <details><summary>remove duplicate <code>elements</code></summary>
diff
__putout_processor_json([ "coverage", "", - "coverage", - "", "abc" ]);
</details> <details><summary>remove duplicate <code>keys</code></summary>
diff
const a = { - x: 'hello', - ...y, x: 'world', ...y, }
</details> <details><summary>remove duplicate <code>case</code></summary>
diff
switch (x) { case 5: console.log('hello'); break; - case 5: - console.log('zz'); - break; }
</details> <details><summary>remove unused <code>private fields</code></summary>
diff
class Hello { #a = 5; - #b = 3; get() { return this.#a; }; }
</details> <details><summary>remove unused <code>expressions</code></summary>
diff
function show(error) { - showError; }
</details> <details><summary>remove useless <code>variables</code></summary>
diff
- function hi(a) { - const b = a; }; + function hi(b) { };
</details> <details><summary>remove useless <code>push</code></summary>
diff
function notUsed() { - const paths = []; for (const [key, name] of tuples) { - paths.push([key, full]); } }
</details> <details><summary>remove useless <code>Object.assign()</code></summary>
diff
-const load = stub().rejects(assign(Error('LOAD USED'))); +const load = stub().rejects(Error('LOAD USED'));
</details> <details><summary>remove useless <code>replace()</code></summary>
diff
-const a = 'hello'.replace(world, world); +const a = 'hello';
</details> <details><summary>remove useless <code>Object.fromEntries()</code></summary>
diff
const a = { - b: Object.fromEntries(Object.entries({ - hello: 'world', - })), + b: { + hello: 'world', + }, };
</details> <details><summary>remove useless <code>replace()</code></summary>
diff
-const a = 'hello'.replace(world, world); +const a = 'hello';
</details> <details><summary>remove useless <code>new</code>(<a href=https://262.ecma-international.org/12.0/#sec-error-constructor>why</a>)</summary>
diff
-new Error('something when wrong'); +Error('something when wrong');
</details> <details><summary>add missing <code>new</code></summary>
diff
-const map = Map(); +const map = new Map();
</details> <details><summary>remove useless <code>constructor</code>(<a href=https://google.github.io/styleguide/tsguide.html#primitive-types-wrapper-classes>why</a>)</summary>
diff
class A extends B() { - constructor(...args) { - super(...args); - } }
</details> <details><summary>remove useless <code>map</code></summary>
diff
-const [str] = lines.map((line) => `hello ${line}`); +const [line] = lines; +const str = `hello ${line}`;
</details> <details><summary>remove useless <code>continue</code></summary>
diff
-for (sign = decpt, i = 0; (sign /= 10) != 0; i++) - continue; +for (sign = decpt, i = 0; (sign /= 10) != 0; i++);
</details> <details><summary>remove useless <code>operand</code></summary>
diff
-a = a + b; +a += b;
</details> <details><summary>remove useless <code>return</code></summary>
diff
-module.exports.traverse = ({push}) => { - return { - ObjectExpression(path) { - } - } -}; +module.exports.traverse = ({push}) => ({ + ObjectExpression(path) { + } +});
</details> <details><summary>remove useless <code>array</code></summary>
diff
-A[[B]]; +A[B];
</details> <details><summary>remove useless <code>array constructor</code></summary>
diff
-const a = Array(1, 2, 3); +const a = [1, 2, 3];
</details> <details><summary>remove useless <code>conditions</code></summary>
diff
-if (zone?.tooltipCallback) { - zone.tooltipCallback(e); -} +zone?.tooltipCallback(e);
</details> <details><summary>remove useless <code>type conversion</code></summary>
diff
-const a = Boolean(b.includes(c)); +const a = b.includes(c); --if (!!a) ++if (a) console.log('hi');
</details> <details><summary>remove useless <code>functions</code></summary>
diff
-const f = (...a) => fn(...a); -array.filter((a) => a); +const f = fn; +array.filter(Boolean);
</details> <details><summary>remove useless <code>typeof</code></summary>
diff
- typeof typeof 'hello'; + typeof 'hello';
</details> <details><summary>declare before <code>reference</code></summary>
diff
-const {compare} = operator; import {operator} from 'putout'; +const {compare} = operator
</details> <details><summary>declare <code>imports</code> first</summary>
diff
-const [arg] = process.argv; import esbuild from 'esbuild'; +const [arg] = process.argv;
</details> <details><summary>declare <code>variables</code></summary>
diff
+const fs = import 'fs/promises'; +const {stub} = import 'supertape'; +const {assign} = Object; const readFile = stub(); assign(fs, { readFile, });
</details> <details><summary>remove useless <code>arguments</code></summary>
diff
onIfStatement({ push, - generate, - abc, }) function onIfStatement({push}) { }
</details> <details><summary>remove useless <code>template expressions</code></summary>
diff
-let y = `${"hello"} + ${"world"}`; +let y = `hello + world`;
</details> <details><summary>remove useless <code>for...of</code></summary>
diff
-for (const a of ['hello']) { - console.log(a); -} +console.log('hello');
</details> <details><summary>remove useless <code><a href=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries>array.entries()</a></code></summary>
diff
-for (const [, element] of array.entries()) { -} +for (const element of array) { +}
</details> <details><summary>reuse duplicate init</summary>
diff
const putout = require('putout'); -const {operator} = require('putout'); +const {operator} = putout;
</details> <details><summary>convert <code>assignment</code> to <code>arrow function</code></summary>
diff
-const createRegExp = (a) = RegExp(a, 'g'); +const createRegExp = (a) => RegExp(a, 'g');
</details> <details><summary>convert <code>assignment</code> to <code>comparison</code></summary>
diff
-if (a = 5) { +if (a === 5) { }
</details> <details><summary>convert <code>arrow function</code> to <code>condition</code></summary>
diff
-if (a => b) {} +if (a >= b) {}
</details> <details><summary>convert <code>quotes</code> to <code>backticks</code></summary>
diff
-const a = 'hello \'world\''; +const a = `hello 'world'`;
</details> <details><summary>convert <code>typeof</code> to <code>is type</code></summary>
diff
+const isFn = (a) => typeof a === 'function'; + +if (isFn(fn)) -if (typeof fn === 'function') fn();
</details> <details><summary>convert <code>bitwise</code> to <code>logical</code></summary>
diff
-a | !b +a || !b
</details> <details><summary>convert <code>equal</code> to <code>strict equal</code></summary>
diff
-if (a == b) { +if (a === b) { }
</details> <details><summary>remove useless <code>escape</code></summary>
diff
-const t = 'hello \"world\"'; -const s1 = `hello \"world\"`; -const s = `hello \'world\'`; +const t = 'hello "world"'; +const s1 = `hello "world"`; +const s = `hello 'world'`;
</details> <details><summary>remove useless <code>Array.from()</code></summary>
diff
-for (const x of Array.from(y)) {} +for (const x of y) {}
</details> <details><summary>remove useless <code>spread</code></summary>
diff
-for (const x of [...y]) {} +for (const x of y) {}
</details> <details><summary>remove <code>debugger</code> statement</summary>
diff
- debugger;
</details> <details><summary>remove <code>iife</code></summary>
diff
-(function() { - console.log('hello world'); -}()); +console.log('hello world');
</details> <details><summary>remove <code>boolean</code> from <code>assertions</code></summary>
diff
-if (a === true) +if (a) alert();
</details> <details><summary>remove <code>boolean</code> from <code>logical expressions</code></summary>
diff
-const t = true && false; +const t = false;
</details> <details><summary>remove nested blocks</summary>
diff
for (const x of Object.keys(a)) { - { - console.log(x); - } + console.log(x); }
</details> <details><summary>remove unreachable code</summary>
diff
function hi() { return 5; - console.log('hello'); }
</details> <details><summary>split variable declarations</summary>
diff
-let a, b; +let a; +let b;
</details> <details><summary>split nested <code>destructuring</code></summary>
diff
-const {a: {b}} = c; +const {a} = c; +const {b} = a;
</details> <details><summary>simplify <code>assignment</code></summary>
diff
-const {a} = {a: 5}; -const [b] = [5]; +const a = 5; +const b = 5;
</details> <details><summary>simplify <code>boolean return</code></summary>
diff
function isA(a, b) { - if (a.length === b.length) - return true; - - return false; + return a.length === b.length; }
</details> <details><summary>simplify <code>logical expressions</code></summary>
diff
-!(options && !options.bidirectional); +!options || options.bidirectional;
</details> <details><summary>simplify <code>ternary</code></summary>
diff
-module.exports = fs.copyFileSync ? fs.copyFileSync : copyFileSync; +module.exports = fs.copyFileSync || copyFileSync;
</details> <details><summary>remove <code>console.log</code> calls</summary>
diff
-console.log('hello');
</details> <details><summary>remove empty block statements</summary>
diff
-if (x > 0) { -}
</details> <details><summary>remove empty patterns</summary>
diff
-const {} = process;
</details> <details><summary>remove <code>constant conditions</code></summary>
diff
function hi(a) { - if (2 < 3) { - console.log('hello'); - console.log('world'); - } + console.log('hello'); + console.log('world'); }; function world(a) { - if (false) { - console.log('hello'); - console.log('world'); - } };
</details> <details><summary>convert <code>replace</code> to <code>replaceAll</code> (<a href=https://github.com/tc39/proposal-string-replaceall>stage-4</a>)</summary>
diff
-'hello'.replace(/hello/g, 'world'); +'hello'.replaceAll('hello', 'world');
</details> <details><summary>apply consistent-blocks</summary>
diff
-if (a) +if (a) { b(); +} else { -else { c(); d(); }
</details> <details><summary>apply arrow</summary>
diff
-export function hello() { - return 'world'; -} +export const hello = () => 'world';
</details> <details><summary>apply destructuring</summary>
diff
-const hello = world.hello; -const a = b[0]; +const {hello} = world; +const [a] = b;
</details> <details><summary>apply early <code>return</code></summary>
diff
function fn() { - if (a) - x(); - else - y(); + if (a) { + x(); + } + y();
</details> <details><summary>apply <code>globalThis</code></summary>
diff
-const {__putout} = global; -const {__putout} = globalThis;
</details> <details><summary>apply dot notation</summary>
diff
-a['hello']['world'] = 5; +a.hello.world = 5;
</details> <details><summary>apply <code>.startsWith()</code></summary>
diff
const {a = ''} = b; -!a.indexOf('>'); +a.startsWith('>');
</details> <details><summary>apply <code>overrides</code></summary>
diff
-export const readRules = (dirOpt, rulesDir, {cwd, readdirSync}) => {} +export const readRules = (dirOpt, rulesDir, overrides) => { const {cwd, readdirSync} = overrides; +}
</details> <details><summary>sort imports by specifiers</summary>
diff
+import a1 from 'a1'; import { a, b, c, d, } from 'd'; -import a1 from 'a1';
</details> <details><summary>apply <code>template literals</code></summary>
diff
-const line = 'hello' + world; +const line = `hello${world}`
</details> <details><summary>apply <code>flatMap()</code></summary>
diff
-array.map(getId).flat(); +array.flatMap(getId);
</details> <details><summary>apply <code>if condition</code></summary>
diff
-if (2 > 3); +if (2 > 3) alert();
</details> <details><summary>apply <code><a href=https://web.mit.edu/jwalden/www/isArray.html>isArray()</a></code></summary>
diff
-x instanceof Array; +Array.isArray(x);
</details> <details><summary>apply <a href=https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V16.md#2021-07-29-version-1660-current-bethgriggs><code>Array.at()</code></a></summary>
diff
-const latest = (a) => a[a.length - 1]; +const latest = (a) => a.at(-1);
</details> <details><summary>apply optional chaining (<a href=https://github.com/tc39/proposal-optional-chaining>proposal-optional-chaining</a>)</summary>
diff
-const result = hello && hello.world; +const result = hello?.world;
</details> <details><summary>apply nullish coalescing (<a href=https://github.com/tc39/proposal-nullish-coalescing>proposal-nullish-coalescing</a>, not bundled)</summary>
diff
-result = typeof result === 'undefined' ? 'hello': result; result = result ?? 'hello';
</details> <details><summary>convert <code>throw</code> statement into expression (<a href=https://github.com/tc39/proposal-throw-expressions>proposal-throw-expressions</a>, not bundled)</summary>
diff
-const fn = (a) => {throw Error(a);} +const fn = (a) => throw Error(a);
</details> <details><summary>merge destructuring properties</summary>
diff
-const {one} = require('numbers'): -const {two} = require('numbers'); + const { + one, + two +} = require('numbers');
</details> <details><summary>merge <code>return</code> with next sibling</summary>
diff
-return -{ - a: 5 -} +return { + a: 5 +};
</details> <details><summary>merge duplicate imports</summary>
diff
-import {m as b} from 'y'; -import {z} from 'y'; -import x from 'y'; +import x, {m as b, z} from 'y';
</details> <details><summary>merge duplicate functions</summary>
diff
const isFn = (a) => typeof a === 'function'; -const isFn1 = (a) => typeof a === 'function'; isFn(1); -isFn1(2); +isFn(2);
</details> <details><summary>merge <code>if</code> statements</summary>
diff
-if (a > b) - if (b < c) - console.log('hi'); +if (a > b && b < c) + console.log('hi');
</details> <details><summary>merge <code>if</code> with <code>else</code></summary>
diff
-if (!matchFn) +if (!matchFn || matchFn(options)) fix(from, to, path); -else if (matchFn(options)) - fix(from, to, path);
</details> <details><summary>convert <code>anonymous</code> to <code>arrow function</code></summary>
diff
-module.exports = function(a, b) { +module.exports = (a, b) => { }
</details> <details><summary>convert <code>for</code> to <code>for...of</code></summary>
diff
-for (let i = 0; i < items.length; i++) { +for (const item of items) { - const item = items[i]; log(item); }
</details> <details><summary>convert <code>forEach</code> to <code>for...of</code></summary>
diff
-Object.keys(json).forEach((name) => { +for (const name of Object.keys(json)) { manage(name, json[name]); -}); +}
</details> <details><summary>convert <code>for...in</code> to <code>for...of</code></summary>
diff
-for (const name in object) { - if (object.hasOwnProperty(name)) { +for (const name of Object.keys(object)) { console.log(a); - } }
</details> <details><summary>convert <code>map</code> to <code>for...of</code></summary>
diff
-names.map((name) => { +for (const name of names) { alert(`hello ${name}`); +} -});
</details> <details><summary>convert <code>reduce</code> to <code>for...of</code></summary>
diff
-const result = list.reduce((a, b) => a + b, 1); +let sum = 1; +for (const a of list) { + sum += a; +}
</details> <details><summary>convert <code>array copy</code> to <code>slice</code></summary>
diff
-const places = [ - ...items, -]; +const places = items.slice();
</details> <details><summary>extract sequence expressions</summary>
diff
-module.exports.x = 1, -module.exports.y = 2; +module.exports.x = 1; +module.exports.y = 2;
</details> <details><summary>extract object properties into variable</summary>
diff
-const {replace} = putout.operator; -const {isIdentifier} = putout.types; +const {operator, types} = putout; +const {replace} = operator; +const {isIdentifier} = types;
</details> <details><summary>convert <code>apply</code> to <code>spread</code></summary>
diff
-console.log.apply(console, arguments); +console.log(...arguments);
</details> <details><summary>convert <code>concat</code> to <code>flat</code></summary>
diff
-[].concat(...array); +array.flat();
</details> <details><summary>convert <code>arguments</code> to <code>rest</code></summary>
diff
-function hello() { - console.log(arguments); +function hello(...args) { + console.log(args); }
</details> <details><summary>convert <code>Object.assign()</code> to <code>merge spread</code></summary>
diff
function merge(a) { - return Object.assign({}, a, { - hello: 'world' - }); + return { + ...a, + hello: 'world' + }; };
</details> <details><summary>convert <code>comparison</code> to <code>boolean</code></summary>
diff
- const a = b === b; + const a = true;
</details> <details><summary>apply comparison order</summary>
diff
-5 === a; +a === 5;
</details> <details><summary>convert <code>const</code> to <code>let</code></summary>
diff
- const a = 5; + let a = 5; a = 3;
</details>

Labels

<details><summary>convert <code>label</code> to <code>object</code></summary>
diff
-const a = () => { - hello: 'world' -} +const a = () => ({ + hello: 'world' +})
</details> <details><summary>remove unused <code>labels</code></summary>
diff
-hello: while (true) { break; }
</details>

Promises

<details><summary>remove useless <code>await</code></summary>
diff
- await await Promise.resolve('hello'); + await Promise.resolve('hello');
</details> <details><summary>remove useless <code>async</code></summary>
diff
-const show = async () => { +const show = () => { console.log('hello'); };
</details> <details><summary>add missing <code>await</code></summary>
diff
-runCli(); +await runCli(); async function runCli() { }
</details> <details><summary>add missing <code>async</code></summary>
diff
-function hello() { +async function hello() { await world(); }
</details> <details><summary>add <code>await</code> to <code>return promise()</code> statements (<a href=https://v8.dev/blog/fast-async>because it's faster, produces call stack and more readable</a>)</summary>
diff
async run () { - return promise(); + return await promise(); }
</details> <details><summary>apply top-level-await (<a href=https://github.com/tc39/proposal-top-level-await>proposal-top-level-await</a>, enabled for ESM)</summary>
diff
import fs from 'fs'; -(async () => { - const data = await fs.promises.readFile('hello.txt'); -})(); +const data = await fs.promises.readFile('hello.txt');
</details> <details><summary>remove useless <code>Promise.resolve()</code></summary>
diff
async () => { - return Promise.resolve('x'); + return 'x'; }
</details> <details><summary>convert <code>Promise.reject()</code> to <code>throw</code></summary>
diff
async () => { - return Promise.reject('x'); + throw 'x'; }
</details> <details><summary>apply <code>await import()</code></summary>
diff
-const {readFile} = import('fs/promises'); +const {readFile} = await import('fs/promises');
</details>

Math

<details><summary>apply numeric separators(<a href=https://github.com/tc39/proposal-numeric-separator>proposal-numeric-separator</a>)</summary>
diff
-const a = 100000000; +const a = 100_000_000;
</details> <details><summary>convert <code>Math.sqrt()</code> to <code>Math.hypot()</code></summary>
diff
-const a = Math.sqrt(b ** 2 + c ** 2); +const a = Math.hypot(a, b);
</details> <details><summary>convert <code>Math.imul()</code> to <code>multiplication</code></summary>
diff
- const a = Math.imul(b, c); + const a = b * c;
</details> <details><summary>convert <code>Math.pow</code> to <code>exponentiation operator</code></summary>
diff
-Math.pow(2, 4); +2 ** 4;
</details>

Node.js

<details><summary>remove <code>strict mode</code> directive from esm</summary>
diff
-'use strict'; - import * from fs;
</details> <details><summary>Add <code>strict mode</code> directive in <code>commonjs</code> if absent</summary>
diff
+'use strict'; + const fs = require('fs');
</details> <details><summary>Add <code>strict mode</code> directive in <code>commonjs</code> if absent</summary>
diff
+'use strict'; + const fs = require('fs');
</details> <details><summary>remove <code>strict mode</code> directive from esm</summary>
diff
-'use strict'; - import * from fs;
</details> <details><summary>Add <code>strict mode</code> directive in <code>commonjs</code> if absent</summary>
diff
+'use strict'; + const fs = require('fs');
</details> <details><summary>remove <code>strict mode</code> directive from esm</summary>
diff
-'use strict'; - import * from fs;
</details> <details><summary>Add <code>strict mode</code> directive in <code>commonjs</code> if absent</summary>
diff
+'use strict'; + const fs = require('fs');
</details> <details><summary>remove <code>strict mode</code> directive from esm</summary>
diff
-'use strict'; - import * from fs;
</details> <details><summary>Add <code>strict mode</code> directive in <code>commonjs</code> if absent</summary>
diff
+'use strict'; + const fs = require('fs');
</details> <details><summary>convert <code>esm</code> to <code>commonjs</code> (disabled)</summary>
diff
-import hello from 'world'; +const hello = require('world');
</details> <details><summary>convert <code>commonjs</code> to <code>esm</code> (disabled)</summary>
diff
-const hello = require('world'); +import hello from 'world';
</details> <details><summary>convert <code>fs.promises</code> to <code>fs/promises</code> for <a href=https://nodejs.org/dist/latest-v15.x/docs/api/fs.html#fs_fs_promises_api>node.js</a></summary>
diff
-const {readFile} = require('fs').promises; +const {readFile} = require('fs/promises');
</details> <details><summary>convert <code>top-level return</code> into <code>process.exit()</code>(because EcmaScript Modules doesn't support top level return)</summary>
diff
- return; + process.exit();
</details> <details><summary>remove <code>process.exit</code> call</summary>
diff
-process.exit();
</details>

Tape

<details><summary>replace <code>test.only</code> with <code>test</code> calls</summary>
diff
-test.only('some test here', (t) => { +test('some test here', (t) => { t.end(); });
</details> <details><summary>replace <code>test.skip</code> with <code>test</code> calls</summary>
diff
-test.skip('some test here', (t) => { +test('some test here', (t) => { t.end(); });
</details>

TypeScript

<details><summary>remove duplicates from <code>union</code></summary>
diff
-type x = boolean[] | A | string | A | string[] | boolean[]; +type x = boolean[] | A | string | string[];
</details> <details><summary>convert <code>generic</code> to <code>shorthand</code>(<a href=https://stackoverflow.com/a/36843084/4536327>why</a>)</summary>
diff
interface A { - x: Array<X>; + x: X[]; }
</details> <details><summary>remove useless <code>types</code> from <code>constants</code></summary>
diff
-const x: any = 5; +const x = 5;
</details> <details><summary>remove useless <code><a href=https://www.typescriptlang.org/docs/handbook/2/mapped-types.html>mapped types</a></code></summary>
diff
-type SuperType = { - [Key in keyof Type]: Type[Key] -} +type SuperType = Type;
</details> <details><summary>remove useless <code><a href=https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#mapping-modifiers>mapping modifiers</a></code></summary>
diff
type SuperType = { - +readonly[Key in keyof Type]+?: Type[Key]; + readonly[Key in keyof Type]?: Type[Key]; }
</details> <details><summary>remove useless <code>types</code></summary>
diff
type oldType = number; -type newType = oldType; -const x: newType = 5; +const x: oldType = 5;
</details> <details><summary>remove duplicate <code>interface</code> keys</summary>
diff
interface Hello { - 'hello': any; 'hello': string; }
</details> <details><summary>remove unused <code>types</code></summary>
diff
type n = number; -type s = string; const x: n = 5;
</details> <details><summary>apply <code>as</code> type assertion (according to <a href=https://basarat.gitbook.io/typescript/type-system/type-assertion#as-foo-vs.-less-than-foo-greater-than>best practices</a>)</summary>
diff
-const boundaryElement = <HTMLElement>e.target; +const boundaryElement1 = e.target as HTMLElement;
</details> <details><summary>apply <a href=https://www.typescriptlang.org/docs/handbook/utility-types.html>utility types</a></summary>
diff
-type SuperType = { - [Key in keyof Type]?: Type[Key]; -} +type SuperType = Partial<Type>;
</details>

🏟 Plugins

The 🐊Putout repo is comprised of many npm packages. It is a Lerna monorepo similar to Babel.
It has a lot of plugins divided by groups:

Appliers

PackageVersion
@putout/plugin-apply-arrownpm
@putout/plugin-apply-consistent-blocksnpm
@putout/plugin-apply-atnpm
@putout/plugin-apply-dot-notationnpm
@putout/plugin-apply-starts-withnpm
@putout/plugin-apply-global-thisnpm
@putout/plugin-apply-flat-mapnpm
@putout/plugin-apply-template-literalsnpm
@putout/plugin-apply-overridesnpm
@putout/plugin-apply-shorthand-propertiesnpm

Mergers

PackageVersion
@putout/plugin-merge-duplicate-functionsnpm

Converters

PackageVersion
@putout/plugin-convert-quotes-to-backticksnpm
@putout/plugin-convert-concat-to-flatnpm
@putout/plugin-convert-array-copy-to-slicenpm
@putout/plugin-convert-template-to-stringnpm
@putout/plugin-convert-index-of-to-includesnpm
@putout/plugin-convert-object-entries-to-array-entriesnpm
@putout/plugin-convert-object-entries-to-object-keysnpm
@putout/plugin-convert-object-keys-to-object-entriesnpm

Removers

PackageVersion
@putout/plugin-remove-unreferenced-variablesnpm
@putout/plugin-remove-duplicate-elementsnpm
@putout/plugin-remove-duplicate-keysnpm
@putout/plugin-remove-duplicate-casenpm
@putout/plugin-remove-unused-expressionsnpm
@putout/plugin-remove-unused-private-fieldsnpm
@putout/plugin-remove-useless-assignnpm
@putout/plugin-remove-useless-replacenpm
@putout/plugin-remove-useless-mapnpm
@putout/plugin-remove-useless-constructornpm
@putout/plugin-remove-useless-continuenpm
@putout/plugin-remove-useless-operandnpm
@putout/plugin-remove-useless-arraynpm
@putout/plugin-remove-useless-array-constructornpm
@putout/plugin-remove-useless-array-entriesnpm
@putout/plugin-remove-useless-object-from-entriesnpm
@putout/plugin-remove-useless-escapenpm
@putout/plugin-remove-useless-functionsnpm
@putout/plugin-remove-useless-pushnpm
@putout/plugin-remove-useless-template-expressionsnpm
@putout/plugin-remove-useless-deletenpm
@putout/plugin-remove-debuggernpm
@putout/plugin-remove-iifenpm
@putout/plugin-remove-unreachable-codenpm
@putout/plugin-remove-consolenpm
@putout/plugin-remove-emptynpm
@putout/plugin-remove-nested-blocksnpm

Simplifiers

PackageVersion
@putout/plugin-simplify-ternarynpm

Declarators

PackageVersion
@putout/plugin-declarenpm
@putout/plugin-declare-before-referencenpm

Groups

PackageVersion
@putout/plugin-argumentsnpm
@putout/plugin-assignmentnpm
@putout/plugin-conditionsnpm
@putout/plugin-destructuringnpm
@putout/plugin-esmnpm
@putout/plugin-filesystemnpm
@putout/plugin-for-ofnpm
@putout/plugin-typesnpm
@putout/plugin-labelsnpm
@putout/plugin-mathnpm
@putout/plugin-madrunnpm
@putout/plugin-optional-chainingnpm
@putout/plugin-parensnpm
@putout/plugin-putoutnpm
@putout/plugin-putout-confignpm
@putout/plugin-returnnpm
@putout/plugin-spreadnpm
@putout/plugin-tapenpm
@putout/plugin-variablesnpm
@putout/plugin-webpacknpm
@putout/plugin-eslintnpm
@putout/plugin-package-jsonnpm
@putout/plugin-promisesnpm
@putout/plugin-generatorsnpm
@putout/plugin-gitignorenpm
@putout/plugin-markdownnpm
@putout/plugin-npmignorenpm
@putout/plugin-coveragenpm
@putout/plugin-browserlistnpm
@putout/plugin-githubnpm
@putout/plugin-regexpnpm
@putout/plugin-nodejsnpm
@putout/plugin-typescriptnpm
@putout/plugin-try-catchnpm
@putout/plugin-montagnpm
@putout/plugin-maybenpm
@putout/plugin-newnpm
@putout/plugin-logical-expressionsnpm
@putout/plugin-dockernpm

Extractors

PackageVersion
@putout/plugin-extract-sequence-expressionsnpm

Not bundled

Next packages not bundled with 🐊Putout but can be installed separately.

PackageVersion
@putout/plugin-apply-entriesnpm
@putout/plugin-eslint-pluginnpm
@putout/plugin-reactnpm
@putout/plugin-react-hook-formnpm
@putout/plugin-nextjsnpm
@putout/plugin-react-routernpm
@putout/plugin-convert-is-nan-to-number-is-nannpm
@putout/plugin-convert-spread-to-array-fromnpm
@putout/plugin-convert-array-copy-to-slicenpm
@putout/plugin-apply-nullish-coalescingnpm
@putout/plugin-cloudcmdnpm
@putout/plugin-postcssnpm
@putout/plugin-jestnpm
@putout/plugin-vitestnpm
@putout/plugin-travisnpm
@putout/plugin-convert-thrownpm
@putout/plugin-printernpm
@putout/plugin-minifynpm
@putout/plugin-socket-ionpm

🦚 Formatters

🐊Putout uses formatters similar to ESLint's formatters.
You can specify a formatter using the --format or -f flag on the command line. For example, --format codeframe uses the codeframe formatter.

The built-in formatter options are:

  • dump
  • stream
  • json
  • json-lines
  • codeframe
  • progress
  • progress-bar
  • frame (codeframe + progress)
  • memory
  • time
PackageVersion
@putout/formatter-dumpnpm
@putout/formatter-streamnpm
@putout/formatter-progressnpm
@putout/formatter-progress-barnpm
@putout/formatter-jsonnpm
@putout/formatter-json-linesnpm
@putout/formatter-codeframenpm
@putout/formatter-framenpm
@putout/formatter-eslintnpm
@putout/formatter-memorynpm
@putout/formatter-timenpm

Custom Formatter

A formatter function executes on every processed file, it should return an output string.

js
export default function formatter({name, source, places, index, count, filesCount, errorsCount}) { return ''; }

Here is list of options:

  • name - name of processed file
  • source - source code of processed file
  • index - current index
  • count - processing files count
  • filesCount - count of files with errors
  • errorsCount count of errors

You can avoid any of this and use only what you need. To make your formatter usable with putout, add the prefix putout-formatter- to your npm package,
and add the tags putout, formatter, putout-formatter.

ESLint Formatters

ESLint formatters can be used as well with help of @putout/formatter-eslint this way:

Install:

npm i putout @putout/formatter-eslint eslint-formatter-pretty -D

Run:

sh
ESLINT_FORMATTER=pretty putout -f eslint lib

πŸ¦‰ Configuration

To configure 🐊Putout add a section named putout to your package.json file or create .putout.json file and override any of default options.

Rules

All rules located in plugins section and built-in rules are enabled by default.
You can disable rules using "off", or enable them (in match section) using "on".

json
{ "rules": { "variables/remove-unused": "off" } }

Or pass options using rules section:

json
{ "rules": { "variables/remove-unused": ["on", { "exclude": "const global = __" }] } }

Exclude

With help of exclude you can set type or code pattern to exclude for current rule.
Pass an array when you have a couple templates to exclude:

json
{ "rules": { "variables/remove-unused": ["on", { "exclude": [ "VariableDeclaration" ] }] } }

exclude is cross-plugin function supported by core, when develop your plugin, please use other name
to keep users ability to customize all plugins in a way they need to.

Match

When you need to match paths to rules you can use match section for this purpose in .putout.json:

json
{ "match": { "server": { "nodejs/remove-process-exit": "on" } } }

Ignore

When you need to ignore some routes no matter what, you can use ignore section in .putout.json:

json
{ "ignore": [ "test/fixture" ] }

Printer

In the eyes of mercy, no one should have hateful thoughts. Feel pity for the man who is even more at fault. The area and size of mercy is limitless.

(c) Yamamoto Tsunetomo "Hagakure"

You have also ability to define printer of your choose, it can be:

@putout/printer used by default, if you want to set any other update .putout.json with:

json
{ "printer": "babel" }

@putout/printer:

  • βœ… much simpler in support then recast;
  • βœ… opinionated and has good defaults;
  • βœ… produces code like it was processed by ESLint;

babel:

You can choose any of them, but preferred is default printer.

Plugins

There are two types of plugin names supported by 🐊Putout, their names in npm start with a prefix:

  • @putout/plugin- for official plugins
  • putout-plugin- for user plugins

ExampleIf you need to remove-something create putout plugin with a name putout-plugin-remove-something and add it to .putout.json:

json
{ "plugins": [ "remove-something" ] }

Add putout as a peerDependency to your packages.json (>= of version you developing for).

☝️ Always add keywords putout, putout-plugin when publish putout plugin to npm so others can easily find it.

🧬 Plugins API

Throughout your life advance daily, becoming more skillful than yesterday more skillful than today. This is never-ending

(c) Yamamoto Tsunetomo "Hagakure"

🐊Putout plugins are the simplest possible way to transform AST and this is for a reason.

And the reason is JavaScript-compatible language 🦎PutoutScript which adds additional meaning to identifiers used in AST-template.

Let's dive into plugin types that you can use for you next code transformation.

Replacer

The simplest 🐊Putout plugin type consists of 2 functions:

  • report - report error message to putout cli;
  • replace - replace key template into value template;
js
export const report = () => 'use optional chaining'; export const replace = () => ({ '__a && __a.__b': '__a?.__b', });

This plugin will find and suggest to replace all occurrences of code: object && object.property into object?.property.

Includer

More powerful plugin type, when you need more control over traversing.
It should contain next 2 functions:

  • report - report error message to putout cli;
  • fix - fixes paths using places array received using find function;

and one or more of this:

  • filter - filter path, should return true, or false (don't use with traverse);
  • include - returns array of templates, or node names to include;
  • exclude - returns array of templates, or node names to exclude;
js
export const report = () => 'use optional chaining'; export const include = () => [ 'debugger', ]; export const fix = (path) => { path.remove(path); };

☝️ Use yeoman generator yo putout, it will generate most of the plugin for you.

☝️ More information about supported plugin types you can find in @putout/engine-runner.

☝️ Find out about the way plugins load in @putout/engine-loader.

☝️ When you need, you can use @babel/types, template and generate. All of this can be gotten from 🐊Putout:

js
import { types, template, generate, } from 'putout';

Operator

When you need to use replaceWith, replaceWithMultiple, or insertAfter, please use operator instead of path-methods.

js
import {template, operator} from 'putout'; const {replaceWith} = operator; const ast = template.ast(` const str = 'hello'; `); export const fix = (path) => { // wrong path.replaceWith(ast); // correct replaceWith(path, ast); };

This should be done to preserve loc and comments information, which is different in Babel and Recast. 🐊Putout will handle this case for you :),
just use the methods of operator.

🐊 Putout Plugin

When you work on a plugin or codemod please add rule putout into .putout.json:

json
{ "rules": { "putout": "on" } }

@putout/plugin-putout will handle plugin-specific cases for you :).

Example

Let's consider simplest possible plugin for removing debugger statements @putout/plugin-remove-debugger:

js
// this is a message to show in putout cli export const report = () => `Avoid 'debugger' statement`; // let's find all "debugger" statements and replace them with "" export const replace = () => ({ debugger: '', });

Visitor used in traverse function can be code template as well. So when you need to find module.exports = <something>, you
can use:

js
export const traverse = ({push}) => ({ 'module.exports = __'(path) { push(path); }, });

Where __ is a placeholder for anything.

☝️Remember: template key should be valid JavaScript, or Node Type, like in previous example.

You can also use include and/or exclude instead of traverse and filter (more sophisticated example):

js
// should be always used include/or exclude, when traverse not used export const include = () => [ 'debugger', ]; // optional export const exclude = () => [ 'console.log', ]; // optional export const filter = (path) => { // do some checks return true; };

Template

There is predefined placeholders:

  • __ - any code;
  • "__" - any string literal;
  • __ - any template string literal;

πŸ“Ό Testing

That was the simplest module to remove debugger statements in your code. Let's look how to test it using @putout/test:

js
import {createTest} from '@putout/test'; import * as removeDebugger from './index.js'; const test = createTest(import.meta.url, { 'remove-debugger': removeDebugger, }); // this is how we test that messages is correct test('remove debugger: report', (t) => { t.reportCode('debugger', `Avoid 'debugger' statement`); t.end(); }); // statement should be removed so result is empty test('remove debugger: transformCode', (t) => { t.transformCode('debugger', ''); t.end(); });

As you see test runner it is little bit extended πŸ“ΌSupertape.
To see a more sophisticated example look at @putout/plugin-remove-console.

πŸ€·β€β™‚οΈ What if I don't want to publish a plugin?

If you don't want to publish a plugin you developed, you can pass it to 🐊Putout as an object described earlier. Here is how it can look like:

js
import * as variables from 'putout/plugin-variables'; putout('const a = 5', { plugins: [ ['variables', variables], ], });

Where plugins is an array that contains [name, implementation] tuples.

πŸ›΄ Codemods

🐊Putout supports codemodes in the similar to plugins way, just create a directory ~/.putout and put your plugins there. Here is example: convert-tape-to-supertape and this is example of work.

πŸ’Ύ Rulesdir

When you have plugins related to your project and you don't want to publish them (because it cannot be reused right now). Use rulesdir:

sh
putout --rulesdir ./rules

This way you can keep rules specific for your project and run them on each lint.

☝️ Remember: if you want to exclude file from loading, add prefix not-rule- and 🐊Putout will ignore it (in the same way as he does with node_modules).

⏣ Integration with ESLint

Find and fix problems in your JavaScript code

(c) eslint.org

If you see that 🐊Putout breaks formatting of your code, use ESLint plugin eslint-plugin-putout.

Install eslint-plugin-putout with:

npm i eslint eslint-plugin-putout -D

Then create .eslintrc.json:

json
{ "extends": [ "plugin:putout/recommended" ], "plugins": ["putout"] }

And use with 🐊Putout this way:

sh
putout --fix lib

To set custom config file for ESLint use ESLINT_CONFIG_FILE env variable:

sh
ESLINT_CONFIG_FILE=test.eslintrc.json putout --fix lib

To disable ESLint support use NO_ESLINT env variable:

sh
NO_ESLINT=1 putout --fix lib

If you want to ignore ESLint warnings (if you for some reason have annoying unfixable errors 🀷) use NO_ESLINT_WARNINGS=1:

sh
NO_ESLINT_WARNINGS=1 putout --fix lib

You can even lint without CLI using ESlint only, since 🐊Putout is bundled to eslint-plugin-putout:

eslint --fix lib

Applies 🐊Putout transformations for you :).

ESLint API

ESLint begins his work as a formatter when 🐊Putout done his transformations. That's why it is used a lot in different parts of application, for testing purpose and using API in a simplest possible way. You can access it using @putout/eslint:

js
import eslint from '@putout/eslint';

To use it simply write:

js
const [source, places] = await eslint({ name: 'hello.js', code: `const t = 'hi'\n`, fix: false, });

Doesn't it look similar to 🐊Putout way? It definitely is! But... It has a couple of differences you should remember:

And you can even override any of ESLint βš™οΈ options with help of config property:

js
const [source, places] = await eslint({ name: 'hello.js', code: `const t = 'hi'\n`, fix: false, config: { extends: [ 'plugin:putout/recommended', ], }, });

If you want to apply 🐊Putout transformations using putout/putout ESLint rule, enable 🐊Putout with the same called flag lowercased:

js
import {recommended} from 'eslint-plugin-putout'; const [source, places] = await eslint({ name: 'hello.js', code: `const t = 'hi'\n`, fix: true, putout: true, config: recommended, });

It is disabled by default, because ESLint always runs after 🐊Putout transformations, so there is no need to traverse tree again.

β˜„οΈ Integration with Babel

🐊 Putout can be used as babel plugin.
Just create .babelrc.json file with configuration you need.

json
{ "plugins": [ ["putout", { "rules": { "variables/remove-unused": "off" } }] ] }

🐈 Integration with Yarn

Since 🐊Putout has dynamic nature of loading:

  • plugins;
  • processors;
  • formatters;

It was a nice adventure to add support of such a wonderful feature of Yarn as Plug'n'Play.
For this purpose new env variable was added to help to load external extensions: PUTOUT_YARN_PNP.

So if you use package eslint-config-hardcore you should run ESLint this way:

sh
PUTOUT_YARN_PNP=eslint-config-hardcore eslint .

πŸšͺExit Codes

🐊Putout can have one of next exit codes:

CodeNameDescriptionOutput Example
0OKno errors found<empty>
1PLACEfound places with errors<violations of rules>
2STAGEnothing in stage<empty>
3NO_FILESno files found🐊 No files matching the pattern "hello" were found
4NO_PROCESSORSno processor found🐊 No processors found for hello.abc
5NO_FORMATTERno formatter found🐊 Cannot find module 'putout-formatter-hello'
6WAS_STOPwas stop<empty or violations of rules>
7INVALID_OPTIONinvalid option🐊 Invalid option '--hello'. Perhaps you meant '--help'
8CANNOT_LOAD_PROCESSORprocessor has errors<unhandled exception>
9CANNOT_LOAD_FORMATTERformatter has errors🐊 @putout/formatter-dump: Syntax error
10RULER_WITH_FIXruler used with --fix🐊 '--fix' cannot be used with ruler toggler ('--enable', '--disable')
11RULER_NO_FILESruler used without files🐊 'path' is missing for ruler toggler ('--enable-all', '--disable-all')
12INVALID_CONFIGconfig has invalid properties🐊 .putout.json: exclude: must NOT have additional properties
13UNHANDLEDunhandled exception<unhandled exception>
14CANNOT_LINT_STAGEDcannot lint staged🐊 --staged: not git repository
15INTERACTIVE_CANCELEDinteractive canceled<empty>
Example of providing invalid option:
sh
coderaiser@localcmd:~/putout$ putout --hello 🐊 Invalid option `--hello`. Perhaps you meant `--help` coderaiser@localcmd:~/putout$ echo $? 7

API

Exit codes enum can be imported as:

js
import {OK} from 'putout/exit-codes';

πŸ¦” Real-world uses

  • Cloud Commander: orthodox file manager for the web.
  • Eslint Config Hardcore: The most strict (but practical) ESLint config out there.
  • Mock Import: Mocking of Node.js EcmaScript Modules.
  • 🏎 Madrun: CLI tool to run multiple npm-scripts in a madly comfortable way.
  • Xterm.js: A terminal for the web.
  • Stylelint: A mighty, modern linter that helps you avoid errors and enforce conventions in your styles.
  • ESTrace: Trace functions in EcmaScript Modules.
  • 🎩ESCover: Coverage for EcmaScript Modules.
  • ♨️ Speca: Write tape tests for you.
  • 🀫Goldstein: JavaScript with no limits.
  • 🎬MadCut: CLI tool to cut markdown into pieces.
  • Minify: a minifier of js, css, html and img files.
  • RedPut - CLI tool to download source of a rule and fixtures from 🐊Putout Editor and generate tests from it.
  • RedLint - Linter for your Filesystem πŸ˜πŸ’Ύ.
  • Bundler - Simplest possible bundler.
  • OpenRewrite - an open-source automated refactoring ecosystem for source code, enabling developers to effectively eliminate technical debt within their repositories.
  • ishvara - compile JavaScript to WASM and Fasm.
  • EsJS - JavaScript con sintaxis en EspaΓ±ol.
  • tsre - a JavaScript and TypeScript reverse engineering tool.
  • aleman - 🐊Putout-based framework for web.
  • bindu - Pāṇini AṣṭādhyāyΔ«.

Are you also use 🐊Putout in your application? Please open a Pull Request to include it here. We would love to have it in our list.

πŸ“» Versioning Policy

Putout follows semantic versioning (semver) principles, with version numbers being on the format major.minor.patch:

  • patch: bug fix, dependency update (17.0.0 -> 17.0.1).
  • minor: new features, new plugins or fixes (17.0.0 -> 17.1.0).
  • major breaking changes, plugins remove (17.0.0 -> 18.0.0).

πŸš€ I want contribute

You can contribute by proposing a feature, fixing a bug or a typo in the documentation.
If you wish to play with code πŸ”₯, you can πŸ’ͺ!
🐊 Putout rejoice and wag its tail when see new contributions πŸ‘Ύ.

πŸ„ License

MIT

Contributors

Showing top 12 contributors by commit count.

View all contributors on GitHub β†’

This article is auto-generated from coderaiser/putout via the GitHub API.Last fetched: 6/21/2026