--- title: JavaScript Codemods. Recursos y ejemplos tags: javascript, codemods, ast lang: es --- # Codemods - [jscodeshift](https://github.com/facebook/jscodeshift) - [API](https://hackmd.io/@yQp_d2iwRF25H5YTCeWj0w/Hy8FL6IWZ?type=view#jscodeshift-In-Depth) - [AST Explorer](http://astexplorer.net/) - [React Codemods (ejemplos)](https://github.com/reactjs/react-codemod) - [Tutorial](https://www.toptal.com/javascript/write-code-to-rewrite-your-code) - [Slides charla MadridJS](https://speakerdeck.com/sanguino/fearless-refactors-con-ast) ## Uso 1. Instalar `jscodeshift` globalmente (`npm i -g jscodeshift`) 2. Ejecutar el codemod sobre el o los archivos que se quieren transformar. Podemos usar globs. Ejemplo sobre un archivo: ```bash= jscodeshift ./dist/assets/bundled.js -t my-codemod.js ``` Ejemplo sobre directorios: ```bash= jscodeshift ./components/prefix-*/*.js -t my-codemod.js ``` ## Ejemplos Reemplaza todos los parĂ¡metros llamados `Element` por `PolymerElement`: ```javascript= export default function(file, api) { const j = api.jscodeshift; return j(file.source) .find(j.VariableDeclarator, { id: { type: 'Identifier', name: 'Element', }, }) .replaceWith(nodePath => { const { node } = nodePath; node.id.name = 'PolymerElement'; return node; }) .toSource(); } ``` Reemplaza el primer bloque encontrado (`{// code}`) por una IIFE: ```javascript= export default function(file, api) { const j = api.jscodeshift; return j(file.source) .find(j.BlockStatement) .at(0) .replaceWith(nodePath => { const nodeValue = nodePath.value; return j.expressionStatement( j.callExpression( j.functionExpression(null, [], j.blockStatement(nodeValue.body)), [] ) ); }) .toSource(); } ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.