From bbb355369fa1a7149115b609289fbef352d8fd15 Mon Sep 17 00:00:00 2001 From: Jack Hsu Date: Thu, 27 Jun 2024 08:51:07 -0400 Subject: [PATCH] fix(nextjs): cleanup and docs --- .../troubleshoot-convert-to-inferred.md | 81 +++++++++++++++---- .../executor-to-plugin-migrator.ts | 7 +- .../lib/build-post-target-transformer.ts | 5 +- .../lib/serve-post-target-tranformer.ts | 35 +++----- 4 files changed, 85 insertions(+), 43 deletions(-) diff --git a/docs/shared/guides/troubleshoot-convert-to-inferred.md b/docs/shared/guides/troubleshoot-convert-to-inferred.md index c82be962683c22..fccc9c5c45dbd0 100644 --- a/docs/shared/guides/troubleshoot-convert-to-inferred.md +++ b/docs/shared/guides/troubleshoot-convert-to-inferred.md @@ -1,6 +1,10 @@ # Troubleshoot Convert to Inferred Migration -Nx comes with plugins that automatically [infer tasks](/concepts/inferred-tasks) (i.e. Project Crystal) for your projects based on the configuration of different tools. Inference plugins come with many benefits, such as reduced boilerplate and access to features such as [task splitting](/ci/features/split-e2e-tasks). To make the transition easier for existing projects that are not yet using inference plugins, many plugins provide the `convert-to-inferred` generator that will switch from executor-based tasks to inferred tasks. +Nx comes with plugins that automatically [infer tasks](/concepts/inferred-tasks) (i.e. Project Crystal) for your +projects based on the configuration of different tools. Inference plugins come with many benefits, such as reduced +boilerplate and access to features such as [task splitting](/ci/features/split-e2e-tasks). To make the transition easier +for existing projects that are not yet using inference plugins, many plugins provide the `convert-to-inferred` generator +that will switch from executor-based tasks to inferred tasks. To see a list of the available migration generators, run: @@ -10,19 +14,29 @@ nx g convert-to-inferred This will prompt you to choose a plugin to run the migration for. -Although the `convert-to-inferred` generator should work for most projects, there are situations that require additional changes to be done by hand. If you run into issues that are not covered on this page, please open an issue on [GitHub](https://github.com/nrwl/nx/issues). +Although the `convert-to-inferred` generator should work for most projects, there are situations that require additional +changes to be done by hand. If you run into issues that are not covered on this page, please open an issue +on [GitHub](https://github.com/nrwl/nx/issues). ## Error: The nx plugin did not find a project inside... -This error occurs when a configuration file matching the tooling cannot be found. For example, Vite works with `vite.config.ts` (or `.js`, `.cts`, `.mts`, etc.). If you've named your configuration file to something unconventional, you must rename it back to the standard naming convention before running the migration generator again. +This error occurs when a configuration file matching the tooling cannot be found. For example, Vite works +with `vite.config.ts` (or `.js`, `.cts`, `.mts`, etc.). If you've named your configuration file to something +unconventional, you must rename it back to the standard naming convention before running the migration generator again. -For example, if you have a `apps/demo/vite.custom.ts` file and are running `nx g @nx/vite:convert-to-inferred`, you must first rename the file to `apps/demo/vite.config.ts` before running the generator. +For example, if you have a `apps/demo/vite.custom.ts` file and are running `nx g @nx/vite:convert-to-inferred`, you must +first rename the file to `apps/demo/vite.config.ts` before running the generator. -## Remix: Unsupported `outputPath` Option +## Remix: Unable to Migrate `outputPath` Option -The [`outputPath`](/nx-api/remix/executors/build#outputpath) option from `@nx/remix:build` is ignored because it often leads to ESM errors when the output path is outside the project root. The ESM error occurs because the root `package.json` may not have `"type": "module"` set, which means that the compiled ESM code will fail to run. To guarantee that `serve` works, we migrate the outputs to the Remix defaults (`build` and `public/build` inside the project root). If you have custom directories already defined in your Remix config, it will continue to be used. +The [`outputPath`](/nx-api/remix/executors/build#outputpath) option from `@nx/remix:build` is ignored because it often +leads to ESM errors when the output path is outside the project root. The ESM error occurs because the +root `package.json` may not have `"type": "module"` set, which means that the compiled ESM code will fail to run. To +guarantee that `serve` works, we migrate the outputs to the Remix defaults (`build` and `public/build` inside the +project root). If you have custom directories already defined in your Remix config, it will continue to be used. -To change the outputs after the migration, edit the remix config file, and look for `serverBuildPath` and `assetsBuildDirectory` and set it to the locations you want. +To change the outputs after the migration, edit the remix config file, and look for `serverBuildPath` +and `assetsBuildDirectory` and set it to the locations you want. ```ts // ... @@ -33,17 +47,24 @@ export default { }; ``` -Note that you will need to address potential ESM issues that may arise. For example, change the root `package.json` to `"type": "module"`. +Note that you will need to address potential ESM issues that may arise. For example, change the root `package.json` +to `"type": "module"`. ## Remix: Unsupported `generatePackageJson` and `generateLockFile` Options -The `generatePackageJson` and `generateLockFile` options in [`@nx/remix:build`](/nx-api/remix/executors/build) cannot currently be migrated. There is support for this feature in the [Nx Vite plugin](/recipes/vite/configure-vite#typescript-paths), so in the future we may be able to support it if using Remix+Vite. +The `generatePackageJson` and `generateLockFile` options in [`@nx/remix:build`](/nx-api/remix/executors/build) cannot +currently be migrated. There is support for this feature in +the [Nx Vite plugin](/recipes/vite/configure-vite#typescript-paths), so in the future we may be able to support it if +using Remix+Vite. ## Storybook: Conflicting `staticDir` Options -Using `staticDir` for both `@nx/storybook:build-storybook` and `@nx/storybook:storybook` executor options will result in the one from `build-storybook` being used in the resulting `.storybook/main.ts` file. It is not possible for us to support both automatically. +Using `staticDir` for both `@nx/storybook:build-storybook` and `@nx/storybook:storybook` executor options will result in +the one from `build-storybook` being used in the resulting `.storybook/main.ts` file. It is not possible for us to +support both automatically. -If you need to differentiate `staticDir` between build and serve, then consider putting logic into your `main.ts` file directly. +If you need to differentiate `staticDir` between build and serve, then consider putting logic into your `main.ts` file +directly. ```ts // ... @@ -60,7 +81,8 @@ export default config; ## Vite: Unsupported `proxyConfig` Option -Projects that used the [`proxyConfig`](/nx-api/vite/executors/dev-server#proxyconfig) option of `@nx/vite:dev-server` will need to inline the proxy configuration from the original file into `vite.config.ts`. +Projects that used the [`proxyConfig`](/nx-api/vite/executors/dev-server#proxyconfig) option of `@nx/vite:dev-server` +will need to inline the proxy configuration from the original file into `vite.config.ts`. For example, if you previously used this in `proxy.config.json`: @@ -90,13 +112,18 @@ export default defineConfig({ ## Webpack: Project Cannot Be Migrated -Projects that use [Nx-enhanced Webpack configuration](/recipes/webpack/webpack-config-setup#nxenhanced-configuration-with-composable-plugins) files cannot be migrated to use Webpack CLI. Nx-enhanced configuration files that contain `composePlugins` and `withNx` require the `@nx/webpack:webpack` executor to work. +Projects that +use [Nx-enhanced Webpack configuration](/recipes/webpack/webpack-config-setup#nxenhanced-configuration-with-composable-plugins) +files cannot be migrated to use Webpack CLI. Nx-enhanced configuration files that contain `composePlugins` and `withNx` +require the `@nx/webpack:webpack` executor to work. To solve this issue, run `nx g @nx/webpack:convert-config-to-webpack-plugin` first, and then try again. ## Webpack: Usage of `useLegacyNxPlugin` -When converting from Nx-enhanced to basic Webpack configuration, we add the `useLegacyNxPlugin` utility to ensure that the functionality of your existing configuration continues to function normally. We recommend that you refactor the configuration such that `useLegacyNxPlugin` is not needed. +When converting from Nx-enhanced to basic Webpack configuration, we add the `useLegacyNxPlugin` utility function to +ensure that your build tasks behave the same after the migration. We recommend that you refactor the configuration such +that `useLegacyNxPlugin` is not needed. For example, if you previously added plugins using the configuration function. @@ -117,7 +144,8 @@ module.exports = async () => ({ }); ``` -If you need to apply configuration changes after `NxAppWebpackPlugin` is applied, then you can create a plugin object as follows. +If you need to apply configuration changes after `NxAppWebpackPlugin` is applied, then you can create a plugin object as +follows. ```js module.exports = async () => ({ @@ -139,3 +167,26 @@ module.exports = async () => ({ ], }); ``` + +## Next.js: Unable to Migrate `outputPath`, `generateLockfile` and `includeDevDependenciesInPackageJson` Options + +The [`outputPath`](/nx-api/remix/executors/build#outputpath) option from `@nx/next:build` is ignored because it +conflicts with Next.js' requirement that [`distDir`](https://nextjs.org/docs/app/api-reference/next-config-js/distDir) +remain inside the project directory. Previously, the `@nx/next:build` executor performed workarounds to bring it outside +the project root, but those workarounds lead to other issues, such as Turbopack not working. + +Since the output directory is now inside the project, we do not generate `package.json` since it is already present. The +lockfile generation support also no longer exists, which does not affect deployments to Vercel, Netlify, or similar +environments. However, it could affect deployments via Docker images where you do not copy the whole monorepo, but +rather just the build artifacts. + +These removals are necessary to align with Next.js recommendations. + +## Next.js: Nx `serve` Only Starts Dev Server + +To better align with Next.js CLI, projects after the migration have two targets to start the server: + +1. `serve` - Starts the dev server (same as `next dev`) +2. `start` - Starts the prod server (same as `next start`) + +Note that `serve` could be different depending on what you used for `@nx/next:server` previously. After the migration, `nx run :serve --prod` not longer starts the prod server. Use `nx run :start` instead. diff --git a/packages/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator.ts b/packages/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator.ts index 88d319212a2bfb..3ffdf037ee818e 100644 --- a/packages/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator.ts +++ b/packages/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator.ts @@ -28,12 +28,15 @@ import type { ConfigurationResult } from 'nx/src/project-graph/utils/project-con import { forEachExecutorOptions } from '../executor-options-utils'; import { deleteMatchingProperties } from './plugin-migration-utils'; +export type InferredTargetConfiguration = TargetConfiguration & { + name: string; +}; type PluginOptionsBuilder = (targetName: string) => T; type PostTargetTransformer = ( targetConfiguration: TargetConfiguration, tree: Tree, projectDetails: { projectName: string; root: string }, - inferredTargetConfiguration: TargetConfiguration + inferredTargetConfiguration: InferredTargetConfiguration ) => TargetConfiguration | Promise; type SkipTargetFilter = ( targetConfiguration: TargetConfiguration @@ -154,7 +157,7 @@ class ExecutorToPluginMigrator { projectTarget, this.tree, { projectName, root: projectFromGraph.data.root }, - createdTarget + { ...createdTarget, name: targetName } ); if ( diff --git a/packages/next/src/generators/convert-to-inferred/lib/build-post-target-transformer.ts b/packages/next/src/generators/convert-to-inferred/lib/build-post-target-transformer.ts index e2ddd1cdd36a9d..d92b3fe56a996b 100644 --- a/packages/next/src/generators/convert-to-inferred/lib/build-post-target-transformer.ts +++ b/packages/next/src/generators/convert-to-inferred/lib/build-post-target-transformer.ts @@ -17,7 +17,6 @@ export function buildPostTargetTransformer(migrationLogs: AggregatedLog) { const configValues = {}; if (target.options) { handlePropertiesFromTargetOptions( - tree, target.options, projectDetails, migrationLogs, @@ -30,7 +29,6 @@ export function buildPostTargetTransformer(migrationLogs: AggregatedLog) { for (const configurationName in target.configurations) { const configuration = target.configurations[configurationName]; handlePropertiesFromTargetOptions( - tree, configuration, projectDetails, migrationLogs, @@ -71,7 +69,7 @@ export function buildPostTargetTransformer(migrationLogs: AggregatedLog) { const options = { ...configValues.default, - //@ts-expect-error: Ignore TypeScript error for indexing configValues with a dynamic key + // @ts-expect-error: Ignore TypeScript error for indexing configValues with a dynamic key ...configValues[configuration], }; `; @@ -81,7 +79,6 @@ export function buildPostTargetTransformer(migrationLogs: AggregatedLog) { } function handlePropertiesFromTargetOptions( - tree: Tree, options: NextBuildBuilderOptions, projectDetails: { projectName: string; root: string }, migrationLogs: AggregatedLog, diff --git a/packages/next/src/generators/convert-to-inferred/lib/serve-post-target-tranformer.ts b/packages/next/src/generators/convert-to-inferred/lib/serve-post-target-tranformer.ts index 551a51e09f9cc0..7d2a885109faf9 100644 --- a/packages/next/src/generators/convert-to-inferred/lib/serve-post-target-tranformer.ts +++ b/packages/next/src/generators/convert-to-inferred/lib/serve-post-target-tranformer.ts @@ -1,33 +1,24 @@ import { TargetConfiguration, Tree } from '@nx/devkit'; import { AggregatedLog } from '@nx/devkit/src/generators/plugin-migrations/aggregate-log-util'; -import { NextServeBuilderOptions } from '../../../utils/types'; +import type { NextServeBuilderOptions } from '../../../utils/types'; +import type { InferredTargetConfiguration } from '@nx/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator'; export function servePosTargetTransformer(migrationLogs: AggregatedLog) { return ( target: TargetConfiguration, - tree: Tree, + _tree: Tree, projectDetails: { projectName: string; root: string }, - inferredTargetConfiguration: TargetConfiguration + inferredTargetConfiguration: InferredTargetConfiguration ) => { if (target.options) { - handlePropertiesFromTargetOptions( - tree, - target.options, - projectDetails.projectName, - migrationLogs - ); + handlePropertiesFromTargetOptions(target.options); } if (target.configurations) { for (const configurationName in target.configurations) { const configuration = target.configurations[configurationName]; - handlePropertiesFromTargetOptions( - tree, - configuration, - projectDetails.projectName, - migrationLogs - ); + handlePropertiesFromTargetOptions(configuration); } if (Object.keys(target.configurations).length === 0) { @@ -45,6 +36,12 @@ export function servePosTargetTransformer(migrationLogs: AggregatedLog) { } } + migrationLogs.addLog({ + project: projectDetails.projectName, + executorName: '@nx/next:server', + log: `Note that "nx run ${projectDetails.projectName}:${inferredTargetConfiguration.name}" only runs the dev server after the migration. To start the prod server, use "nx run ${projectDetails.projectName}:start".`, + }); + return target; }; } @@ -64,13 +61,7 @@ const executorFieldsToRemain: Array = [ const camelCaseToKebabCase = (str: string) => str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`); -// TODO(nicholas): Clean up this function -function handlePropertiesFromTargetOptions( - tree: Tree, - options: NextServeBuilderOptions, - projectName: string, - migrationLogs: AggregatedLog -) { +function handlePropertiesFromTargetOptions(options: NextServeBuilderOptions) { Object.keys(options).forEach((key) => { if ( !executorFieldsToRename.includes(key as keyof NextServeBuilderOptions) &&