From 99164baaa00559dd29998f2d055a409b42f77cf2 Mon Sep 17 00:00:00 2001 From: Isaac Mann Date: Thu, 2 Dec 2021 14:25:50 -0500 Subject: [PATCH] docs(devkit): example of jscodeshift codemod (#7976) Co-authored-by: Isaac Mann --- .../shared/generators/composing-generators.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/shared/generators/composing-generators.md b/docs/shared/generators/composing-generators.md index 04186e0cb6..21b3dfb4c0 100644 --- a/docs/shared/generators/composing-generators.md +++ b/docs/shared/generators/composing-generators.md @@ -16,3 +16,27 @@ export default async function (tree: Tree, schema: any) { ); } ``` + +## Using jscodeshift Codemods + +Codemods created for use with [`jscodeshift`](https://github.com/facebook/jscodeshift) can be used within Nx Devkit generators using the `visitNotIgnoredFiles` helper function. This way you can compose codemods with other generators while retaining `--dry-run` and Nx Console compatibilities. + +```typescript +import { Tree, visitNotIgnoredFiles } from '@nrwl/devkit'; +import { applyTransform } from 'jscodeshift/src/testUtils'; +import arrowFunctionsTransform from './arrow-functions'; + +// The schema path can be an individual file or a directory +export default async function (tree: Tree, schema: { path: string }): any { + visitNotIgnoredFiles(tree, schema.path, (filePath) => { + const input = tree.read(filePath).toString(); + const transformOptions = {}; + const output = applyTransform( + { default: arrowFunctionsTransform, parser: 'ts' }, + transformOptions, + { source: input, path: filePath } + ); + tree.write(filePath, output); + }); +} +```