What is @types/jscodeshift?
@types/jscodeshift provides TypeScript type definitions for the jscodeshift library, which is a toolkit for running codemods over multiple JavaScript or TypeScript files. It allows developers to programmatically transform code using abstract syntax trees (ASTs).
What are @types/jscodeshift's main functionalities?
Transforming Code
This feature allows you to transform code by manipulating its AST. In this example, all identifier names in the source code are reversed.
const jscodeshift = require('jscodeshift');
const transform = (fileInfo, api) => {
const j = api.jscodeshift;
return j(fileInfo.source)
.find(j.Identifier)
.forEach(path => {
path.node.name = path.node.name.split('').reverse().join('');
})
.toSource();
};
module.exports = transform;
Finding Nodes
This feature allows you to find specific nodes in the AST. In this example, it finds all identifier nodes in the source code.
const jscodeshift = require('jscodeshift');
const findIdentifiers = (source) => {
const j = jscodeshift;
return j(source)
.find(j.Identifier)
.nodes();
};
module.exports = findIdentifiers;
Replacing Nodes
This feature allows you to replace specific nodes in the AST. In this example, it replaces all identifiers with a given name with a new name.
const jscodeshift = require('jscodeshift');
const replaceIdentifiers = (source, oldName, newName) => {
const j = jscodeshift;
return j(source)
.find(j.Identifier, { name: oldName })
.replaceWith(path => j.identifier(newName))
.toSource();
};
module.exports = replaceIdentifiers;
Other packages similar to @types/jscodeshift
recast
Recast is a JavaScript library for rewriting JavaScript code. It provides a way to parse, modify, and print JavaScript code while preserving the original formatting. Compared to jscodeshift, recast focuses more on preserving the original code's formatting and structure.
esprima
Esprima is a high-performance, standard-compliant ECMAScript parser. It is used to parse JavaScript code into an AST. While it does not provide transformation capabilities out of the box like jscodeshift, it can be used in conjunction with other tools to analyze and transform code.