Gathering detailed insights and metrics for @putout/plugin-remove-useless-continue
Gathering detailed insights and metrics for @putout/plugin-remove-useless-continue
Gathering detailed insights and metrics for @putout/plugin-remove-useless-continue
Gathering detailed insights and metrics for @putout/plugin-remove-useless-continue
🐊 Pluggable and configurable JavaScript Linter, code transformer and formatter, drop-in ESLint superpower replacement 💪 with built-in support for js, jsx, typescript, flow, markdown, yaml and json. Write declarative codemods in a simplest possible way 😏
npm install @putout/plugin-remove-useless-continue
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
711 Stars
14,160 Commits
40 Forks
10 Watching
46 Branches
22 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (99.04%)
TypeScript (0.69%)
HTML (0.18%)
WebAssembly (0.05%)
CSS (0.03%)
Svelte (0.01%)
Cumulative downloads
Total Downloads
Last day
108.2%
5,787
Compared to previous day
Last week
7%
15,973
Compared to previous week
Last month
25.2%
65,949
Compared to previous month
Last year
52.8%
554,397
Compared to previous year
1
6
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 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 a lot 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:
are also supported. Here is how it looks like:
CommonJS
to ESM
Check out couple variants of plugins that does the same: linting debugger statement:
1'use strict'; 2 3module.exports.report = () => `Unexpected 'debugger' statement`; 4 5module.exports.replace = () => ({ 6 debugger: '', 7});
Choose wisely, competitors cannot even fix… 🤫
🐊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.
If I have seen further, it is by standing upon the shoulders of giants.
(c) Isaac Newton
🐊Putout on the other hand can make more drastic code transformations that directly affects your codebase making it a better place to code 💻:
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.
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'
--flow enable flow
--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
:
1echo 'PATH="$PATH:node_modules/.bin"' >> ~/.bashrc 2source ~/.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
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.
🐊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
When you need to run 🐊Putout in Deno, use @putout/bundle
:
1import putout from 'https://esm.sh/@putout/bundle'; 2import removeDebugger from 'https://esm.sh/@putout/plugin-remove-debugger?alias=putout:@putout/bundle'; 3import declare from 'https://esm.sh/@putout/plugin-declare?alias=putout:@putout/bundle'; 4 5putout('isFn(fn); debugger', { 6 plugins: [ 7 ['remove-debugger', removeDebugger], 8 ['declare', declare], 9 ], 10}); 11 12// returns 13({ 14 code: `const isFn = a => typeof a === 'function';\nisFn(fn);`, 15 places: [], 16});
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')
You may want to convert your CommonJS
to ESM
since node v12 supports it without a flag.
CommonJS
to ESM
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
.
.cjs
or .mjs
filesThey will be converted automatically to CommonJS
and ESM
accordingly.
Let's suppose you have a file called index.js
:
1const unused = 5; 2 3module.exports = function() { 4 return promise(); 5}; 6 7async function promise(a) { 8 return Promise.reject(Error('x')); 9}
You call putout --fix index.js
and see that file is changed:
1'use strict'; 2 3module.exports = async function() { 4 return await promise(); 5}; 6 7async function promise() { 8 throw Error('x'); 9}
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:
1 1:4 error 'unused' is defined but never used remove-unused-variables 2 7:23 error 'a' is defined but never used remove-unused-variables 3 3:0 error Use arrow function convert-to-arrow-function 4 1:0 error Add missing 'use strict' directive on top of CommonJS mode/add-missing 5 8:4 error Reject is useless in async functions, use throw instead promises/convert-reject-to-throw 6 4:11 error Async functions should be called using 'await' promises/add-missing-await 7 7:0 error Avoid useless async promises/remove-useless-async
It will create config file .putout.json
:
1{ 2 "rules": { 3 "remove-unused-variables": "off", 4 "convert-to-arrow-function": "off", 5 "nodejs/strict-mode-add-missing": "off", 6 "promises/convert-reject-to-throw": "off", 7 "promises/add-missing-await": "off", 8 "promises/remove-useless-async": "off" 9 } 10}
Then running putout index.js --enable nodejs/convert-commonjs-to-esm
will update config with:
1{ 2 "rules": { 3 "remove-unused-variables": "off", 4 "convert-to-arrow-function": "off", 5 "nodejs/strict-mode-add-missing": "off", 6 "promises/convert-reject-to-throw": "off", 7 "promises/add-missing-await": "off", 8- "promises/remove-useless-async": "off" 9+ "promises/remove-useless-async": "off", 10+ "nodejs/convert-commonjs-to-esm": "on" 11 } 12}
Then putout --fix index.js
will do the thing and update index.js
with:
1const unused = 5; 2 3export default function() { 4 return promise(); 5} 6 7async function promise(a) { 8 return Promise.reject(Error('x')); 9}
So in case of src
directory, it will look like:
1putout 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 🎈!
🐊Putout consists of a couple simple parts, here is a workflow representation:
And here is a CLI scheme:
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
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:
1hello = 'world';
It looks this way in ESTree JavaScript syntax format:
1{ 2 "type": "AssignmentExpression", 3 "operator": "=", 4 "left": { 5 "type": "Identifier", 6 "name": "hello" 7 }, 8 "right": { 9 "type": "StringLiteral", 10 "value": "world" 11 } 12}
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.
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 is the heart of 🐊Putout: Parser, Loader and Runner are running for every processed file. Processor runs all the processors.
Package | Version |
---|---|
@putout/engine-parser | |
@putout/engine-loader | |
@putout/engine-runner | |
@putout/engine-processor | |
@putout/engine-reporter |
With help of processors 🐊Putout can be extended to read any file format and parse JavaScript from there.
Here is a list of built-int processors:
Package | Version |
---|---|
@putout/processor-javascript | |
@putout/processor-json | |
@putout/processor-markdown | |
@putout/processor-ignore | |
@putout/processor-yaml | |
@putout/processor-css | |
@putout/processor-filesystem |
You can disable any of them with:
1{ 2 "processors": [ 3 ["markdown", "off"] 4 ] 5}
Not bundled processors:
Package | Version |
---|---|
@putout/processor-typescript | |
@putout/processor-html | |
@putout/processor-wasm |
External processors:
Package | Version |
---|---|
putout-processor-typos |
To enable, install and use:
1{ 2 "processors": [ 3 ["typescript", "on"] 4 ] 5}
Processors can be tested using @putout/test/processors.
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.
First things first, require
putout:
1const putout = require('putout');
Let's consider the next source
with two VariableDeclarations
and one CallExpression
:
1const hello = 'world'; 2const hi = 'there'; 3 4console.log(hello);
We can declare it as source
:
1const source = ` 2 const hello = 'world'; 3 const hi = 'there'; 4 5 console.log(hello); 6`;
🐊Putout supports dynamic loading of plugins from node_modules
. Let's consider example of using the remove-unused-variables plugin:
1putout(source, { 2 plugins: [ 3 'remove-unused-variables', 4 ], 5}); 6 7// returns 8({ 9 code: `\n const hello = 'world';\n\n console.log(hello);\n`, 10 places: [], 11});
As you see, places
is empty, but the code is changed: there is no hi
variable.
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:
1putout(source, { 2 fix: false, 3 plugins: [ 4 'remove-unused-variables', 5 ], 6}); 7 8// returns 9({ 10 code: '\n' + ` const hello = 'world';\n` + ` const hi = 'there';\n` + ' \n' + ' console.log(hello);\n', 11 places: [{ 12 rule: 'remove-unused-variables', 13 message: '"hi" is defined but never used', 14 position: { 15 line: 3, 16 column: 10, 17 }, 18 }], 19});
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.
In our case Data URL
used. Here is an example of source map:
1{ 2 "version": 3, 3 "file": "out.js", 4 "sourceRoot": "", 5 "sources": [ 6 "foo.js", 7 "bar.js" 8 ], 9 "names": [ 10 "src", 11 "maps", 12 "are", 13 "fun" 14 ], 15 "mappings": "AAgBC,SAAQ,CAAEA" 16}
To generate source map you need to pass:
sourceFileName
;sourceMapName
;1putout(source, { 2 fix: false, 3 sourceFileName: 'hello.js', 4 sourceMapName: 'world.js', 5 plugins: [ 6 'remove-unused-variables', 7 ], 8}); 9 10// returns 11({ 12 code: ` 13 const hello = 'world'; 14 const hi = 'there'; 15 console.log(hello); 16 //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJ... 17 `, 18 places: [{ 19 rule: 'remove-unused-variables', 20 message: '"hi" is defined but never used', 21 position: { 22 line: 3, 23 column: 10, 24 }, 25 }], 26});
unused variables
1 function show() { 2- const message = 'hello'; 3 console.log('hello world'); 4 }
for...of
variables1-for (const {a, b} of c) { 2+for (const {a} of c) { 3 console.log(a); 4}
unreferenced variables
1-let a; 2- a = 1; 3let b; 4b = 2; 5console.log(b);
keys
1const a = { 2- x: 'hello', 3- ...y, 4 x: 'world', 5 ...y, 6}
case
1switch (x) { 2 case 5: 3 console.log('hello'); 4 break; 5- case 5: 6- console.log('zz'); 7- break; 8}
private fields
1 class Hello { 2 #a = 5; 3- #b = 3; 4 get() { 5 return this.#a; 6 }; 7}
expressions
1 function show(error) { 2- showError; 3 }
variables
1- function hi(a) { 2- const b = a; 3 }; 4+ function hi(b) { 5 };
push
1 function notUsed() { 2- const paths = []; 3 for (const [key, name] of tuples) { 4- paths.push([key, full]); 5 } 6 }
Object.assign()
1-const load = stub().rejects(assign(Error('LOAD USED'))); 2+const load = stub().rejects(Error('LOAD USED'));
replace()
1-const a = 'hello'.replace(world, world); 2+const a = 'hello';
new
(why)1-new Error('something when wrong'); 2+Error('something when wrong');
new
1-const map = Map(); 2+const map = new Map();
constructor
(why)1class A extends B() { 2- constructor(...args) { 3- super(...args); 4- } 5}
map
1-const [str] = lines.map((line) => `hello ${line}`); 2+const [line] = lines; 3+const str = `hello ${line}`;
continue
1-for (sign = decpt, i = 0; (sign /= 10) != 0; i++) 2- continue; 3+for (sign = decpt, i = 0; (sign /= 10) != 0; i++);
operand
1-a = a + b; 2+a += b;
return
1-module.exports.traverse = ({push}) => { 2- return { 3- ObjectExpression(path) { 4- } 5- } 6-}; 7+module.exports.traverse = ({push}) => ({ 8+ ObjectExpression(path) { 9+ } 10+});
array
1-A[[B]]; 2+A[B];
array constructor
1-const a = Array(1, 2, 3); 2+const a = [1, 2, 3];
conditions
1-if (zone?.tooltipCallback) { 2- zone.tooltipCallback(e); 3-} 4+zone?.tooltipCallback(e);
type conversion
1-const a = Boolean(b.includes(c)); 2+const a = b.includes(c); 3 4--if (!!a) 5++if (a) 6 console.log('hi'); 7
functions
1-const f = (...a) => fn(...a); 2-array.filter((a) => a); 3 4+const f = fn; 5+array.filter(Boolean);
typeof
1- typeof typeof 'hello'; 2+ typeof 'hello';
reference
1-const {compare} = operator; 2import {operator} from 'putout'; 3+const {compare} = operator
imports
first1-const [arg] = process.argv; 2import esbuild from 'esbuild'; 3+const [arg] = process.argv;
variables
1+const fs = import 'fs/promises'; 2+const {stub} = import 'supertape'; 3+const {assign} = Object; 4 5const readFile = stub(); 6assign(fs, { 7 readFile, 8});
arguments
1onIfStatement({ 2 push, 3- generate, 4- abc, 5}) 6 7function onIfStatement({push}) { 8}
template expressions
1-let y = `${"hello"} + ${"world"}`; 2+let y = `hello + world`;
for...of
1-for (const a of ['hello']) { 2- console.log(a); 3-} 4+console.log('hello');
array.entries()
1-for (const [, element] of array.entries()) { 2-} 3+for (const element of array) { 4+}
1const putout = require('putout'); 2-const {operator} = require('putout'); 3+const {operator} = putout;
assignment
to arrow function
1-const createRegExp = (a) = RegExp(a, 'g'); 2+const createRegExp = (a) => RegExp(a, 'g');
assignment
to comparison
1-if (a = 5) { 2+if (a === 5) { 3}
arrow function
to condition
1-if (a => b) {} 2+if (a >= b) {}
quotes
to backticks
1-const a = 'hello \'world\''; 2+const a = `hello 'world'`;
typeof
to is type
1+const isFn = (a) => typeof a === 'function'; 2+ 3+if (isFn(fn)) 4-if (typeof fn === 'function') 5 fn();
bitwise
to logical
1-a | !b 2+a || !b
equal
to strict equal
1-if (a == b) { 2+if (a === b) { 3}
escape
1-const t = 'hello \"world\"'; 2-const s1 = `hello \"world\"`; 3-const s = `hello \'world\'`; 4+const t = 'hello "world"'; 5+const s1 = `hello "world"`; 6+const s = `hello 'world'`;
Array.from()
1-for (const x of Array.from(y)) {} 2+for (const x of y) {}
spread
1-for (const x of [...y]) {} 2+for (const x of y) {}
debugger
statement1- debugger;
iife
1-(function() { 2- console.log('hello world'); 3-}()); 4+console.log('hello world');
boolean
from assertions
1-if (a === true) 2+if (a) 3 alert();
boolean
from logical expressions
1-const t = true && false; 2+const t = false;
1for (const x of Object.keys(a)) { 2- { 3- console.log(x); 4- } 5+ console.log(x); 6}
1function hi() { 2 return 5; 3- console.log('hello'); 4}
1-let a, b; 2+let a; 3+let b;
destructuring
1-const {a: {b}} = c; 2+const {a} = c; 3+const {b} = a;
assignment
1-const {a} = {a: 5}; 2-const [b] = [5]; 3+const a = 5; 4+const b = 5;
boolean return
1function isA(a, b) { 2- if (a.length === b.length) 3- return true; 4- 5- return false; 6+ return a.length === b.length; 7}
logical expressions
1-!(options && !options.bidirectional); 2+!options || options.bidirectional;
ternary
1-module.exports = fs.copyFileSync ? fs.copyFileSync : copyFileSync; 2+module.exports = fs.copyFileSync || copyFileSync;
console.log
calls1-console.log('hello');
1-if (x > 0) { 2-}
1-const {} = process;
constant conditions
1function hi(a) { 2- if (2 < 3) { 3- console.log('hello'); 4- console.log('world'); 5- } 6+ console.log('hello'); 7+ console.log('world'); 8}; 9 10function world(a) { 11- if (false) { 12- console.log('hello'); 13- console.log('world'); 14- } 15};
replace
to replaceAll
(stage-4)1-'hello'.replace(/hello/g, 'world'); 2+'hello'.replaceAll('hello', 'world');
1-if (a) 2+if (a) { 3 b(); 4+} else { 5-else { 6 c(); 7 d(); 8}
1-const hello = world.hello; 2-const a = b[0]; 3+const {hello} = world; 4+const [a] = b;
1-a['hello']['world'] = 5; 2+a.hello.world = 5;
.startsWith()
1const {a = ''} = b; 2-!a.indexOf('>'); 3+a.startsWith('>');
overrides
1-export const readRules = (dirOpt, rulesDir, {cwd, readdirSync}) => {} 2+export const readRules = (dirOpt, rulesDir, overrides) => { 3 const {cwd, readdirSync} = overrides; 4+}
1+import a1 from 'a1'; 2import { 3 a, 4 b, 5 c, 6 d, 7} from 'd'; 8-import a1 from 'a1';
template literals
1-const line = 'hello' + world; 2+const line = `hello${world}`
flatMap()
1-array.map(getId).flat(); 2+array.flatMap(getId);
if condition
1-if (2 > 3); 2+if (2 > 3) 3 alert();
isArray()
1-x instanceof Array; 2+Array.isArray(x);
Array.at()
1-const latest = (a) => a[a.length - 1]; 2+const latest = (a) => a.at(-1);
1-const result = hello && hello.world; 2+const result = hello?.world;
1-result = typeof result === 'undefined' ? 'hello': result; 2result = result ?? 'hello';
throw
statement into expression (proposal-throw-expressions, not bundled)1-const fn = (a) => {throw Error(a);} 2+const fn = (a) => throw Error(a);
1-const {one} = require('numbers'): 2-const {two} = require('numbers'); 3+ const { 4+ one, 5+ two 6+} = require('numbers');
1-import {m as b} from 'y'; 2-import {z} from 'y'; 3-import x from 'y'; 4+import x, {m as b, z} from 'y';
1const isFn = (a) => typeof a === 'function'; 2-const isFn1 = (a) => typeof a === 'function'; 3 4isFn(1); 5-isFn1(2); 6+isFn(2);
if
statements1-if (a > b) 2- if (b < c) 3- console.log('hi'); 4+if (a > b && b < c) 5+ console.log('hi');
anonymous
to arrow function
1-module.exports = function(a, b) { 2+module.exports = (a, b) => { 3}
for
to for...of
1-for (let i = 0; i < items.length; i++) { 2+for (const item of items) { 3- const item = items[i]; 4 log(item); 5}
forEach
to for...of
1-Object.keys(json).forEach((name) => { 2+for (const name of Object.keys(json)) { 3 manage(name, json[name]); 4-}); 5+}
for...in
to for...of
1-for (const name in object) { 2- if (object.hasOwnProperty(name)) { 3+for (const name of Object.keys(object)) { 4 console.log(a); 5- } 6}
map
to for...of
1-names.map((name) => { 2+for (const name of names) { 3 alert(`hello ${name}`); 4+} 5-});
reduce
to for...of
1-const result = list.reduce((a, b) => a + b, 1); 2+let sum = 1; 3+for (const a of list) { 4+ sum += a; 5+}
array copy
to slice
1-const places = [ 2- ...items, 3-]; 4+const places = items.slice();
1-module.exports.x = 1, 2-module.exports.y = 2; 3+module.exports.x = 1; 4+module.exports.y = 2;
1-const {replace} = putout.operator; 2-const {isIdentifier} = putout.types; 3+const {operator, types} = putout; 4+const {replace} = operator; 5+const {isIdentifier} = types;
apply
to spread
1-console.log.apply(console, arguments); 2+console.log(...arguments);
concat
to flat
1-[].concat(...array); 2+array.flat();
arguments
to rest
1-function hello() { 2- console.log(arguments); 3+function hello(...args) { 4+ console.log(args); 5}
Object.assign()
to merge spread
1function merge(a) { 2- return Object.assign({}, a, { 3- hello: 'world' 4- }); 5+ return { 6+ ...a, 7+ hello: 'world' 8+ }; 9};
comparison
to boolean
1- const a = b === b; 2+ const a = true;
1-5 === a; 2+a === 5;
const
to let
1- const a = 5; 2+ let a = 5; 3 a = 3;
label
to object
1-const a = () => { 2- hello: 'world' 3-} 4+const a = () => ({ 5+ hello: 'world' 6+})
labels
1-hello: 2while (true) { 3 break; 4}
await
1- await await Promise.resolve('hello'); 2+ await Promise.resolve('hello');
async
1-const show = async () => { 2+const show = () => { 3 console.log('hello'); 4};
await
1-runCli(); 2+await runCli(); 3 4async function runCli() { 5}
async
1-function hello() { 2+async function hello() { 3 await world(); 4}
await
to return promise()
statements (because it's faster, produces call stack and more readable)1async run () { 2- return promise(); 3+ return await promise(); 4}
1import fs from 'fs'; 2 3-(async () => { 4- const data = await fs.promises.readFile('hello.txt'); 5-})(); 6+const data = await fs.promises.readFile('hello.txt');
Promise.resolve()
1async () => { 2- return Promise.resolve('x'); 3+ return 'x'; 4}
Promise.reject()
to throw
1async () => { 2- return Promise.reject('x'); 3+ throw 'x'; 4}
await import()
1-const {readFile} = import('fs/promises'); 2+const {readFile} = await import('fs/promises');
1-const a = 100000000; 2+const a = 100_000_000;
Math.sqrt()
to Math.hypot()
1-const a = Math.sqrt(b ** 2 + c ** 2); 2+const a = Math.hypot(a, b);
Math.imul()
to multiplication
1- const a = Math.imul(b, c); 2+ const a = b * c;
Math.pow
to exponentiation operator
1-Math.pow(2, 4); 2+2 ** 4;
strict mode
directive from esm1-'use strict'; 2- 3import * from fs;
strict mode
directive in commonjs
if absent1+'use strict'; 2+ 3const fs = require('fs');
strict mode
directive in commonjs
if absent1+'use strict'; 2+ 3const fs = require('fs');
strict mode
directive from esm1-'use strict'; 2- 3import * from fs;
strict mode
directive in commonjs
if absent1+'use strict'; 2+ 3const fs = require('fs');
strict mode
directive from esm1-'use strict'; 2- 3import * from fs;
strict mode
directive in commonjs
if absent1+'use strict'; 2+ 3const fs = require('fs');
strict mode
directive from esm1-'use strict'; 2- 3import * from fs;
strict mode
directive in commonjs
if absent1+'use strict'; 2+ 3const fs = require('fs');
esm
to commonjs
(disabled)1-import hello from 'world'; 2+const hello = require('world');
commonjs
to esm
(disabled)1-const hello = require('world'); 2+import hello from 'world';
fs.promises
to fs/promises
for node.js1-const {readFile} = require('fs').promises; 2+const {readFile} = require('fs/promises');
top-level return
into process.exit()
(because EcmaScript Modules doesn't support top level return)1- return; 2+ process.exit();
process.exit
call1-process.exit();
test.only
with test
calls1-test.only('some test here', (t) => { 2+test('some test here', (t) => { 3 t.end(); 4});
test.skip
with test
calls1-test.skip('some test here', (t) => { 2+test('some test here', (t) => { 3 t.end(); 4});
union
1-type x = boolean[] | A | string | A | string[] | boolean[]; 2+type x = boolean[] | A | string | string[];
generic
to shorthand
(why)1interface A { 2- x: Array<X>; 3+ x: X[]; 4}
types
from constants
1-const x: any = 5; 2+const x = 5;
mapped types
1-type SuperType = { 2- [Key in keyof Type]: Type[Key] 3-} 4+type SuperType = Type;
mapping modifiers
1type SuperType = { 2- +readonly[Key in keyof Type]+?: Type[Key]; 3+ readonly[Key in keyof Type]?: Type[Key]; 4}
types
1type oldType = number; 2-type newType = oldType; 3-const x: newType = 5; 4+const x: oldType = 5;
interface
keys1interface Hello { 2- 'hello': any; 3 'hello': string; 4}
types
1type n = number; 2-type s = string; 3const x: n = 5;
as
type assertion (according to best practices)1-const boundaryElement = <HTMLElement>e.target; 2+const boundaryElement1 = e.target as HTMLElement;
1-type SuperType = { 2- [Key in keyof Type]?: Type[Key]; 3-} 4+type SuperType = Partial<Type>;
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:
Package | Version |
---|---|
@putout/plugin-sort-imports-by-specifiers |
Package | Version |
---|---|
@putout/plugin-split-assignment-expressions | |
@putout/plugin-split-variable-declarations | |
@putout/plugin-split-nested-destructuring |
Package | Version |
---|---|
@putout/plugin-merge-destructuring-properties | |
@putout/plugin-merge-duplicate-imports | |
@putout/plugin-merge-duplicate-functions |
Package | Version |
---|---|
@putout/plugin-simplify-assignment | |
@putout/plugin-simplify-ternary | |
@putout/plugin-simplify-boolean-return |
Package | Version |
---|---|
@putout/plugin-declare | |
@putout/plugin-declare-imports-first | |
@putout/plugin-declare-before-reference |
Package | Version |
---|---|
@putout/plugin-extract-sequence-expressions | |
@putout/plugin-extract-object-properties |
Package | Version |
---|---|
@putout/plugin-reuse-duplicate-init |
Package | Version |
---|---|
@putout/plugin-group-imports-by-source |
Next packages not bundled with 🐊Putout but can be installed separately.
🐊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
A formatter function executes on every processed file, it should return an output string
.
1export default function formatter({name, source, places, index, count, filesCount, errorsCount}) { 2 return ''; 3}
Here is list of options:
name
- name of processed filesource
- source code of processed fileindex
- current indexcount
- processing files countfilesCount
- count of files with errorserrorsCount
count of errorsYou 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 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:
1ESLINT_FORMATTER=pretty putout -f eslint lib
To configure 🐊Putout add a section named putout
to your package.json
file or create .putout.json
file and override any of default options.
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"
.
1{ 2 "rules": { 3 "remove-unused-variables": "off" 4 } 5}
Or pass options using rules
section:
1{ 2 "rules": { 3 "remove-unused-variables": ["on", { 4 "exclude": "const global = __" 5 }] 6 } 7}
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:
1{ 2 "rules": { 3 "remove-unused-variables": ["on", { 4 "exclude": [ 5 "VariableDeclaration" 6 ] 7 }] 8 } 9}
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.
When you need to match paths to rules you can use match
section for this purpose in .putout.json
:
1{ 2 "match": { 3 "server": { 4 "nodejs/remove-process-exit": "on" 5 } 6 } 7}
When you need to ignore some routes no matter what, you can use ignore
section in .putout.json
:
1{ 2 "ignore": [ 3 "test/fixture" 4 ] 5}
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:
1{ 2 "printer": "recast" 3}
@putout/printer
:
recast
;recast
;recast
:
eslint-plugin-putout
;babel
:
recast
;You can choose any of them, but preferred is default printer.
There are two types of plugin names supported by 🐊Putout, their names in npm start with a prefix:
@putout/plugin-
for official pluginsputout-plugin-
for user pluginsExample
If you need to remove-something
create putout
plugin with a name putout-plugin-remove-something
and add it to .putout.json
:
1{ 2 "plugins": [ 3 "remove-something" 4 ] 5}
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.
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.
The simplest 🐊Putout plugin type consists of 2 functions:
report
- report error message to putout
cli;replace
- replace key
template into value
template;1module.exports.report = () => 'use optional chaining'; 2module.exports.replace = () => ({ 3 '__a && __a.__b': '__a?.__b', 4});
This plugin will find and suggest to replace all occurrences of code: object && object.property
into object?.property
.
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;1module.exports.report = () => 'use optional chaining'; 2module.exports.include = () => ['debugger']; 3 4module.exports.fix = (path) => { 5 path.remove(path); 6};
☝️ 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:
1const { 2 types, 3 template, 4 generate, 5} = require('putout');
When you need to use replaceWith
, replaceWithMultiple
, or insertAfter
, please use operator
instead of path
-methods.
1const {template, operator} = require('putout'); 2const {replaceWith} = operator; 3 4const ast = template.ast(` 5 const str = 'hello'; 6`); 7 8module.exports.fix = (path) => { 9 // wrong 10 path.replaceWith(ast); 11 // correct 12 replaceWith(path, ast); 13};
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
.
When you work on a plugin
or codemod
please add rule putout
into .putout.json
:
1{ 2 "rules": { 3 "putout": "on" 4 } 5}
@putout/plugin-putout will handle plugin-specific cases for you :).
Let's consider simplest possible plugin for removing debugger statements
@putout/plugin-remove-debugger:
1// this is a message to show in putout cli 2module.exports.report = () => 'Unexpected "debugger" statement'; 3// let's find all "debugger" statements and replace them with "" 4module.exports.replace = () => ({ 5 debugger: '', 6});
Visitor
used in traverse function
can be code template as well. So when you need to find module.exports = <something>
, you
can use:
1module.exports.traverse = ({push}) => ({ 2 'module.exports = __'(path) { 3 push(path); 4 }, 5});
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):
1// should be always used include/or exclude, when traverse not used 2module.exports.include = () => ['debugger']; 3// optional 4module.exports.exclude = () => [ 5 'console.log', 6]; 7 8// optional 9module.exports.filter = (path) => { 10 // do some checks 11 return true; 12};
There is predefined placeholders:
__
- any code;"__"
- any string literal;__
- any template string literal;That was the simplest module to remove debugger
statements in your code. Let's look how to test it using @putout/test:
1const removeDebugger = require('..'); 2 3const test = require('@putout/test')(__dirname, { 4 'remove-debugger': removeDebugger, 5}); 6 7// this is how we test that messages is correct 8test('remove debugger: report', (t) => { 9 t.reportCode('debugger', 'Unexpected "debugger" statement'); 10 t.end(); 11}); 12 13// statement should be removed so result is empty 14test('remove debugger: transformCode', (t) => { 15 t.transformCode('debugger', ''); 16 t.end(); 17});
As you see test runner it is little bit extended 📼Supertape. To see a more sophisticated example look at @putout/plugin-remove-console.
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:
1putout('const a = 5', { 2 plugins: [ 3 ['remove-unused-variables', require('@putout/plugin-remove-unused-variables')], 4 ], 5});
Where plugins
is an array
that contains [name, implementation]
tuples
.
🐊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
:
1putout --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 for node_modules
).
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
:
1{ 2 "extends": [ 3 "plugin:putout/recommended" 4 ], 5 "plugins": ["putout"] 6}
And use with 🐊Putout this way:
1putout --fix lib
To set custom config file for ESLint use ESLINT_CONFIG_FILE
env variable:
1ESLINT_CONFIG_FILE=test.eslintrc.json putout --fix lib
To disable ESLint support use NO_ESLINT
env variable:
1NO_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
:
1NO_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 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
:
1import eslint from '@putout/eslint';
To use it simply write:
1const [source, places] = await eslint({ 2 name: 'hello.js', 3 code: `const t = 'hi'\n`, 4 fix: false, 5});
Doesn't it look similar to 🐊Putout way? It definitely is! But... It has a couple of differences you should remember:
code
and places
properties.name
property that is used to calculate configuration file.And you can even override any of ESLint ⚙️ options with help of config
property:
1const [source, places] = await eslint({ 2 name: 'hello.js', 3 code: `const t = 'hi'\n`, 4 fix: false, 5 config: { 6 extends: [ 7 'plugin:putout/recommended', 8 ], 9 }, 10});
If you want to apply 🐊Putout transformations using putout/putout
ESLint rule, enable 🐊Putout with the same called flag lowercased:
1const [source, places] = await eslint({ 2 name: 'hello.js', 3 code: `const t = 'hi'\n`, 4 fix: true, 5 putout: true, 6 config: { 7 extends: [ 8 'plugin:putout/recommended', 9 ], 10 }, 11});
It is disabled by default, because ESLint always runs after 🐊Putout transformations, so there is no need to traverse tree again.
🐊 Putout can be used as babel plugin.
Just create .babelrc.json
file with configuration you need.
1{ 2 "plugins": [ 3 ["putout", { 4 "rules": { 5 "remove-unused-variables": "off" 6 } 7 }] 8 ] 9}
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:
1PUTOUT_YARN_PNP=eslint-config-hardcore eslint .
🐊Putout can be used as loader this way:
1node --import putout/register your-file.js
You can also transform input files using Babel
. For example if you need to transform jsx
with @babel/plugin-transform-react-jsx
you can use .putout.json
:
1{ 2 "plugins": [ 3 "babel/transform-react-jsx" 4 ] 5}
🐊Putout can have one of next exit codes:
Code | Name | Description | Output Example |
---|---|---|---|
0 | OK | no errors found | <empty> |
1 | PLACE | found places with errors | <violations of rules> |
2 | STAGE | nothing in stage | <empty> |
3 | NO_FILES | no files found | 🐊 No files matching the pattern "hello" were found |
4 | NO_PROCESSORS | no processor found | 🐊 No processors found for hello.abc |
5 | NO_FORMATTER | no formatter found | 🐊 Cannot find module 'putout-formatter-hello' |
6 | WAS_STOP | was stop | <empty or violations of rules> |
7 | INVALID_OPTION | invalid option | 🐊 Invalid option '--hello'. Perhaps you meant '--help' |
8 | CANNOT_LOAD_PROCESSOR | processor has errors | <unhandled exception> |
9 | CANNOT_LOAD_FORMATTER | formatter has errors | 🐊 @putout/formatter-dump: Syntax error |
10 | RULLER_WITH_FIX | ruller used with --fix | 🐊 '--fix' cannot be used with ruler toggler ('--enable', '--disable') |
11 | RULLER_NO_FILES | ruller used without files | 🐊 'path' is missing for ruler toggler ('--enable-all', '--disable-all') |
12 | INVALID_CONFIG | config has invalid properties | 🐊 .putout.json: exclude: must NOT have additional properties |
13 | UNHANDLED | unhandled exception | <unhandled exception> |
14 | CANNOT_LINT_STAGED | cannot lint staged | 🐊 --staged: not git repository |
15 | INTERACTIVE_CANCELED | interactive canceled | <empty> |
Example of providing invalid option:
1coderaiser@localcmd:~/putout$ putout --hello 2🐊 Invalid option `--hello`. Perhaps you meant `--help` 3coderaiser@localcmd:~/putout$ echo $? 47
Exit codes enum
can be imported as:
1import {OK} from 'putout/exit-codes';
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.
Putout follows semantic versioning (semver) principles, with version numbers being on the format major.minor.patch:
bug fix
, dependency update
(17.0.0 -> 17.0.1
).new features
, new plugins
or fixes
(17.0.0 -> 17.1.0
).breaking changes
, plugins remove
(17.0.0 -> 18.0.0
).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 👾.
MIT
No vulnerabilities found.
Reason
30 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
no binaries found in the repo
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
security policy file not detected
Details
Reason
no SAST tool detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More