├── .babelrc ├── .gitignore ├── README.md ├── package.json ├── playground ├── .gitignore ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt ├── src │ ├── components │ │ └── Button.tsx │ └── index.tsx ├── tsconfig.json └── yarn.lock ├── transforms ├── __testfixtures__ │ ├── use-strict.input.js │ └── use-strict.output.js ├── __tests__ │ └── use-strict-test.js ├── absolute-to-relative-imports.js └── use-strict.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"], 3 | "plugins": ["@babel/plugin-proposal-object-rest-spread"] 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Codemods 2 | 3 | A list of useful codemods 4 | 5 | ## Getting started 6 | 7 | Install [jscodeshift](https://github.com/facebook/jscodeshift) into your application or codebase. Find the transform you want to use, copy it down and follow instructions. Starting with a clean git branch is useful. 8 | 9 | ```sh 10 | yarn add jscodeshift --dev 11 | ``` 12 | 13 | ## Transforms 14 | 15 | ### `absolute-to-relative-imports` 16 | 17 | Converts absolute imports to relative ones. 18 | 19 | ```diff 20 | - import { Button } @/components/Button` 21 | + import { Button } from '../../correct/relative/path/components/Button' 22 | ``` 23 | 24 | Open `absolute-to-relative-imports.js` and modify the `pathMapping` variable at the top of the file before running. 25 | 26 | ```js 27 | /** 28 | * Corresponds to tsconfig.json paths or webpack aliases 29 | * E.g. "@/app/store/AppStore" -> "./src/app/store/AppStore" 30 | */ 31 | const pathMapping = { 32 | '@/components': './src/components', 33 | }; 34 | ``` 35 | 36 | Execute the codemod on your `src` directory. 37 | 38 | ```sh 39 | ## TypeScript 40 | ./node_modules/.bin/jscodeshift -t ./transforms/absolute-to-relative-imports.js src/**.tsx src/**.ts --parser=tsx 41 | 42 | ## JavaScript 43 | ./node_modules/.bin/jscodeshift -t ./transforms/absolute-to-relative-imports.js src/**.js 44 | ``` 45 | 46 | ### `use-strict` 47 | 48 | Adds `'use strict'` to files 49 | 50 | ```diff 51 | + 'use strict' 52 | function foo() { 53 | console.log('boop'); 54 | } 55 | ``` 56 | 57 | ```sh 58 | ## TypeScript 59 | ./node_modules/.bin/jscodeshift -t ./transforms/use-strict.js src/**.tsx src/**.ts --parser=tsx 60 | 61 | ## JavaScript 62 | ./node_modules/.bin/jscodeshift -t ./transforms/use-strict.js src/**.js 63 | ``` 64 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "codemod", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "test": "jest", 7 | "test:watch": "jest --watch" 8 | }, 9 | "dependencies": { 10 | "jscodeshift": "^0.9.0" 11 | }, 12 | "jest": { 13 | "globals": { 14 | "baseDir": "../../../" 15 | }, 16 | "roots": [ 17 | "transforms/__tests__" 18 | ] 19 | }, 20 | "devDependencies": { 21 | "@babel/core": "^7.10.1", 22 | "@babel/plugin-proposal-object-rest-spread": "^7.10.1", 23 | "@babel/preset-env": "^7.10.1", 24 | "babel-jest": "^26.0.1", 25 | "jest": "^26.0.1" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /playground/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /playground/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /playground/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "playground", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.3.2", 8 | "@testing-library/user-event": "^7.1.2", 9 | "@types/jest": "^24.0.0", 10 | "@types/node": "^12.0.0", 11 | "@types/react": "^16.9.0", 12 | "@types/react-dom": "^16.9.0", 13 | "react": "^16.13.1", 14 | "react-dom": "^16.13.1", 15 | "react-scripts": "3.4.1", 16 | "typescript": "~3.7.2" 17 | }, 18 | "scripts": { 19 | "start": "react-scripts start", 20 | "build": "react-scripts build", 21 | "test": "react-scripts test", 22 | "eject": "react-scripts eject" 23 | }, 24 | "eslintConfig": { 25 | "extends": "react-app" 26 | }, 27 | "browserslist": { 28 | "production": [ 29 | ">0.2%", 30 | "not dead", 31 | "not op_mini all" 32 | ], 33 | "development": [ 34 | "last 1 chrome version", 35 | "last 1 firefox version", 36 | "last 1 safari version" 37 | ] 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /playground/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredpalmer/codemods/c305e9f3a979d077e5e692370c3ac51123a21e7e/playground/public/favicon.ico -------------------------------------------------------------------------------- /playground/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /playground/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredpalmer/codemods/c305e9f3a979d077e5e692370c3ac51123a21e7e/playground/public/logo192.png -------------------------------------------------------------------------------- /playground/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredpalmer/codemods/c305e9f3a979d077e5e692370c3ac51123a21e7e/playground/public/logo512.png -------------------------------------------------------------------------------- /playground/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /playground/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /playground/src/components/Button.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | export interface ButtonProps {} 4 | 5 | export const Button: React.FC = ({ children }) => { 6 | return ; 7 | }; 8 | 9 | Button.displayName = 'Button'; 10 | -------------------------------------------------------------------------------- /playground/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { Button } from 'components/Button'; 4 | 5 | function App() { 6 | return ; 7 | } 8 | ReactDOM.render( 9 | 10 | 11 | , 12 | document.getElementById('root') 13 | ); 14 | 15 | // If you want your app to work offline and load faster, you can change 16 | // unregister() to register() below. Note this comes with some pitfalls. 17 | // Learn more about service workers: https://bit.ly/CRA-PWA 18 | serviceWorker.unregister(); 19 | -------------------------------------------------------------------------------- /playground/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "esModuleInterop": true, 8 | "allowSyntheticDefaultImports": true, 9 | "strict": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "noEmit": true, 16 | "jsx": "react", 17 | "baseUrl": "src" 18 | }, 19 | "include": ["src"] 20 | } 21 | -------------------------------------------------------------------------------- /transforms/__testfixtures__/use-strict.input.js: -------------------------------------------------------------------------------- 1 | function x() { 2 | console.log('Banana'); 3 | } 4 | -------------------------------------------------------------------------------- /transforms/__testfixtures__/use-strict.output.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | function x() { 3 | console.log('Banana'); 4 | } 5 | -------------------------------------------------------------------------------- /transforms/__tests__/use-strict-test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const defineTest = require('jscodeshift/dist/testUtils').defineTest; 4 | 5 | const printOptions = { 6 | quote: 'single', 7 | }; 8 | defineTest(__dirname, 'use-strict', { printOptions }); 9 | -------------------------------------------------------------------------------- /transforms/absolute-to-relative-imports.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | /** 3 | * Corresponds to tsconfig.json paths or webpack aliases 4 | * E.g. "@/app/store/AppStore" -> "./src/app/store/AppStore" 5 | */ 6 | const pathMapping = { 7 | components: './src/components', 8 | }; 9 | 10 | function replacePathAlias(currentFilePath, importPath, pathMap) { 11 | // if windows env, convert backslashes to "/" first 12 | currentFilePath = path.posix.join(...currentFilePath.split(path.sep)); 13 | const regex = createRegex(pathMap); 14 | return importPath.replace(regex, replacer); 15 | 16 | function replacer(_, alias, rest) { 17 | const mappedImportPath = pathMap[alias] + rest; 18 | 19 | // use path.posix to also create foward slashes on windows environment 20 | let mappedImportPathRelative = path.posix.relative( 21 | path.dirname(currentFilePath), 22 | mappedImportPath 23 | ); 24 | // append "./" to make it a relative import path 25 | if (!mappedImportPathRelative.startsWith('../')) { 26 | mappedImportPathRelative = `./${mappedImportPathRelative}`; 27 | } 28 | 29 | logReplace(currentFilePath, mappedImportPathRelative); 30 | 31 | return mappedImportPathRelative; 32 | } 33 | } 34 | 35 | function createRegex(pathMap) { 36 | const mapKeysStr = Object.keys(pathMap).reduce((acc, cur) => `${acc}|${cur}`); 37 | const regexStr = `^(${mapKeysStr})(.*)$`; 38 | return new RegExp(regexStr, 'g'); 39 | } 40 | 41 | const log = true; 42 | function logReplace(currentFilePath, mappedImportPathRelative) { 43 | if (log) 44 | console.log( 45 | 'current processed file:', 46 | currentFilePath, 47 | '; Mapped import path relative to current file:', 48 | mappedImportPathRelative 49 | ); 50 | } 51 | 52 | module.exports = function transform(file, api, options) { 53 | const j = api.jscodeshift; 54 | const root = j(file.source); 55 | 56 | root.find(j.ImportDeclaration).forEach(replaceNodepathAliases); 57 | root.find(j.ExportAllDeclaration).forEach(replaceNodepathAliases); 58 | 59 | /** 60 | * Filter out normal module exports, like export function foo(){ ...} 61 | * Include export {a} from "mymodule" etc. 62 | */ 63 | root 64 | .find(j.ExportNamedDeclaration, (node) => node.source !== null) 65 | .forEach(replaceNodepathAliases); 66 | 67 | return root.toSource(); 68 | 69 | function replaceNodepathAliases(impExpDeclNodePath) { 70 | impExpDeclNodePath.value.source.value = replacePathAlias( 71 | file.path, 72 | impExpDeclNodePath.value.source.value, 73 | pathMapping 74 | ); 75 | } 76 | }; 77 | -------------------------------------------------------------------------------- /transforms/use-strict.js: -------------------------------------------------------------------------------- 1 | module.exports = (file, api, options) => { 2 | const j = api.jscodeshift; 3 | 4 | const hasStrictMode = (body) => 5 | body.some((statement) => 6 | j.match(statement, { 7 | type: 'ExpressionStatement', 8 | expression: { 9 | type: 'Literal', 10 | value: 'use strict', 11 | }, 12 | }) 13 | ); 14 | 15 | const withComments = (to, from) => { 16 | to.comments = from.comments; 17 | return to; 18 | }; 19 | 20 | const createUseStrictExpression = () => 21 | j.expressionStatement(j.literal('use strict')); 22 | 23 | const root = j(file.source); 24 | const body = root.get().value.program.body; 25 | if (!body.length || hasStrictMode(body)) { 26 | return null; 27 | } 28 | 29 | body.unshift(withComments(createUseStrictExpression(), body[0])); 30 | body[0].comments = body[1].comments; 31 | delete body[1].comments; 32 | 33 | return root.toSource(options.printOptions || { quote: 'single' }); 34 | }; 35 | --------------------------------------------------------------------------------