Skip to content

Instantly share code, notes, and snippets.

@caseywatts
Last active January 31, 2020 10:21
Show Gist options
  • Save caseywatts/b8fffb51180fe44cd3706407d61150a3 to your computer and use it in GitHub Desktop.
Save caseywatts/b8fffb51180fe44cd3706407d61150a3 to your computer and use it in GitHub Desktop.
Sharing jscodeshift codemods

codemod-cli is straightforward - but it's especially made for codemod projects that have multiple transforms. For a single transform, we could/should have a simpler interface for consumers.

Here are three ways to share your codemod with others. The npx methods require you npm publish the repo.

Method 1 - global install, using githubusercontent

Easiest method for the developer, especially if you only have one transform and/or if you're not using codemod-cli. This uses the github-hosted raw.githubusercontent link to run it, kinda like running it from a gist. Here's an example using ember-mocha-codemods.

npm install -g jscodeshift
jscodeshift -t https://raw.githubusercontent.com/Turbo87/ember-mocha-codemods/master/new-testing-api.js path/to/files

Method 2 - npx with codemod-cli

If you're set up with codemod-cli, it's pretty simple to use npx with it! The drawback here is if you only have one transform, the 2nd argument is redundant - and if you didn't set up the project with codemod-cli you'd have to migrate the files to that structure (there should be a codemod for this! ahaha)

npx my-jscodeshift-project my-transform-name path/to/files

Method 3 - npx bin shim

For a single transform, this would be my favorite interface. This is especially good for users who don't want to globally install jscodeshift. It would also help prevent issues with version incompatibility etc (I had one of those just now!).

I don't know how to make this work yet, but it should be possible somehow.

npx my-codeshift-project path/to/files

npx will call the default bin file (either a sh file or .js in this case, and it needs chmod +x on it to work)

Something like this bin/cli file I have, but in the context of the npx package:

#!/bin/sh
jscodeshift -t  $@
  • This would then (ideally) call something like npm run codemod which runs jscodeshift -t ... for you in the context of the npm package, with the right version and all.

Method 4 - development style

This is what I use when working on developing a codemod, to see how it would work on a repo I have locally. Consumers could do this too

git clone https://github.com/caseywatts/ember-cli-mirage-faker-codemod
cd ember-cli-mirage-faker-codemod
npm install
npm run codemod path/to/directories/or/files/you/want

where you have a package json with command codemod

  "scripts": {
    "codemod": "jscodeshift -t transform.js"
  },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment