Migration Generators

When your plugin is being used in other repos, it is helpful to provide migration generators to automatically update configuration files when your plugin makes a breaking change.

A migration generator is a normal generator that is triggered when a developer runs the nx migrate command.

Create a Migration Generator

For this example, we'll create a new migration generator that updates repos to use newExecutorName instead of oldExecutorName in their targets. This migration will be applied when the run nx migrate to move up past version 2.0.1 of our plugin.

1. Generate a migration

nx generate @nx/plugin:migration 'Change Executor Name' --packageVersion=2.0.1 --project=pluginName --description='Changes the executor name from oldExecutorName to newExecutorName'

This command will update the following files:

package.json
1{ 2 "nx-migrations": { 3 "migrations": "./migrations.json" 4 } 5} 6
migrations.json
1{ 2 "generators": { 3 "change-executor-name": { 4 "version": "2.0.1", 5 "description": "Changes the executor name from oldExecutorName to newExecutorName", 6 "cli": "nx", 7 "implementation": "./src/migrations/change-executor-name/change-executor-name" 8 } 9 } 10} 11

And it creates a blank generator under: libs/pluginName/src/migrations/change-executor-name/change-executor-name.ts

2. Write the Generator Code

change-executor-name.ts
1import { getProjects, Tree, updateProjectConfiguration } from '@nx/devkit'; 2 3export function changeExecutorNameToNewName(tree: Tree) { 4 const projects = getProjects(tree); 5 6 for (const [name, project] of projects) { 7 if ( 8 project.targets?.build?.executor === '@myorg/pluginName:oldExecutorName' 9 ) { 10 project.targets.build.executor = '@myorg/pluginName:newExecutorName'; 11 updateProjectConfiguration(tree, name, project); 12 } 13 } 14} 15 16export default changeExecutorNameToNewName; 17

Update package.json dependencies

If you just need to change dependency versions, you can add some configuration options to the migrations.json file without making a full generator.

migrations.json
1{ 2 "packageJsonUpdates": { 3 // this can be any name 4 "12.10.0": { 5 // this is version at which the change will be applied 6 "version": "12.10.0-beta.2", 7 "packages": { 8 // the name of the dependency to update 9 "@testing-library/react": { 10 // the version to set the dependency to 11 "version": "11.2.6", 12 // When true, the dependency will be added if it isn't there. When false, the dependency is skipped if it isn't already present. 13 "alwaysAddToPackageJson": false 14 } 15 } 16 } 17 } 18} 19