Skip to content

Commit

Permalink
fix(nextjs): cleanup and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysoo committed Jun 27, 2024
1 parent de2f217 commit 915eb74
Show file tree
Hide file tree
Showing 5 changed files with 147 additions and 57 deletions.
100 changes: 85 additions & 15 deletions docs/shared/guides/troubleshoot-convert-to-inferred.md
Original file line number Diff line number Diff line change
@@ -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:

Expand All @@ -10,19 +14,69 @@ 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
## Next.js: Unable to Migrate `outputPath`, `generateLockfile` and `includeDevDependenciesInPackageJson` Options

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/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.

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 customize the output directory, set `distDir` in your Next.js config file.

```js
const configuration = process.env.NX_TASK_TARGET_CONFIGURATION || 'default';
// ...
const nextConfig = {
nx: {
...options,
},
// Differentiate production and development builds. You can also use the `configuration` variable that will match the `--configuration` option passed to Nx.
distDir: process.env.NODE_ENV === 'production' ? 'dist' : 'dist-dev',
};
const plugins = [withNx];
module.exports = composePlugins(...plugins)(nextConfig);
```

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 <proj>:serve --prod` not longer starts the prod server. Use `nx run <proj>:start` instead.

## 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.

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
// ...
Expand All @@ -33,17 +87,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
// ...
Expand All @@ -60,7 +121,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`:

Expand Down Expand Up @@ -90,13 +152,20 @@ 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](/recipes/webpack/webpack-config-setup#nxenhanced-configuration-with-composable-plugins) 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.

Expand All @@ -117,7 +186,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 () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> = (targetName: string) => T;
type PostTargetTransformer = (
targetConfiguration: TargetConfiguration,
tree: Tree,
projectDetails: { projectName: string; root: string },
inferredTargetConfiguration: TargetConfiguration
inferredTargetConfiguration: InferredTargetConfiguration
) => TargetConfiguration | Promise<TargetConfiguration>;
type SkipTargetFilter = (
targetConfiguration: TargetConfiguration
Expand Down Expand Up @@ -154,7 +157,7 @@ class ExecutorToPluginMigrator<T> {
projectTarget,
this.tree,
{ projectName, root: projectFromGraph.data.root },
createdTarget
{ ...createdTarget, name: targetName }
);

if (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import {
addProjectConfiguration,
joinPathFragments,
readNxJson,
readProjectConfiguration,
writeJson,
type ExpandedPluginConfiguration,
joinPathFragments,
type ProjectConfiguration,
type ProjectGraph,
readNxJson,
readProjectConfiguration,
type Tree,
writeJson,
} from '@nx/devkit';
import { TempFs } from '@nx/devkit/internal-testing-utils';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
Expand Down Expand Up @@ -253,12 +253,13 @@ describe('convert-to-inferred', () => {
});
});

it('should move fileReplacement option to withNx', async () => {
it('should move fileReplacement and assets option to withNx', async () => {
const project = createProject(
tree,
{},
{
build: {
assets: [{ input: 'tools', output: '.', glob: 'test.txt' }],
fileReplacements: [
{
replace: 'apps/my-app/environments/environment.ts',
Expand All @@ -285,13 +286,20 @@ describe('convert-to-inferred', () => {
with: './environments/environment.foo.ts',
},
],
assets: [
{
input: '../../tools',
output: '../..',
glob: 'test.txt',
},
],
},
development: {},
};
const configuration = process.env.NX_TASK_TARGET_CONFIGURATION || 'default';
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],
};
/**
Expand Down Expand Up @@ -366,4 +374,27 @@ describe('convert-to-inferred', () => {
}
`);
});

it('should migrate options to CLI options and args', async () => {
const project = createProject(
tree,
{},
{
build: {
experimentalAppOnly: true,
experimentalBuildMode: true,
},
}
);
writeNextConfig(tree, project.root);

await convertToInferred(tree, { project: project.name });

const projectConfig = readProjectConfiguration(tree, project.name);
expect(projectConfig.targets.build).toMatchObject({
options: {
args: ['--experimental-app-only', '--experimental-build-mode'],
},
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export function buildPostTargetTransformer(migrationLogs: AggregatedLog) {
const configValues = {};
if (target.options) {
handlePropertiesFromTargetOptions(
tree,
target.options,
projectDetails,
migrationLogs,
Expand All @@ -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,
Expand Down Expand Up @@ -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],
};
`;
Expand All @@ -81,7 +79,6 @@ export function buildPostTargetTransformer(migrationLogs: AggregatedLog) {
}

function handlePropertiesFromTargetOptions(
tree: Tree,
options: NextBuildBuilderOptions,
projectDetails: { projectName: string; root: string },
migrationLogs: AggregatedLog,
Expand All @@ -94,7 +91,7 @@ function handlePropertiesFromTargetOptions(
migrationLogs.addLog({
project: projectDetails.projectName,
executorName: '@nx/next:build',
log: 'Unable to migrate `outputPath` to Next.js Config as it may lead to unexpected behavior. Please use the `distDir` option in your next.config.js file instead.',
log: 'Unable to migrate `outputPath` to Next.js config as it may lead to unexpected behavior. Please use the `distDir` option in your next.config.js file instead.',
});
delete options.outputPath;
}
Expand Down Expand Up @@ -129,7 +126,7 @@ function handlePropertiesFromTargetOptions(
migrationLogs.addLog({
project: projectDetails.projectName,
executorName: '@nx/next:build',
log: "Unable to migrate `includeDevDependenciesInPackageJson` to Next.js Config. Use the `@nx/dependency-checks` ESLint rule to update your project's package.json.",
log: "Unable to migrate `includeDevDependenciesInPackageJson` to Next.js config. Use the `@nx/dependency-checks` ESLint rule to update your project's package.json.",
});

delete options.includeDevDependenciesInPackageJson;
Expand All @@ -139,7 +136,7 @@ function handlePropertiesFromTargetOptions(
migrationLogs.addLog({
project: projectDetails.projectName,
executorName: '@nx/next:build',
log: "Unable to migrate `generatePackageJson` to Next.js Config. Use the `@nx/dependency-checks` ESLint rule to update your project's package.json.",
log: "Unable to migrate `generatePackageJson` to Next.js config. Use the `@nx/dependency-checks` ESLint rule to update your project's package.json.",
});

delete options.generatePackageJson;
Expand All @@ -149,7 +146,7 @@ function handlePropertiesFromTargetOptions(
migrationLogs.addLog({
project: projectDetails.projectName,
executorName: '@nx/next:build',
log: 'Unable to migrate `generateLockfile` to Next.js Config. This option is not supported.',
log: 'Unable to migrate `generateLockfile` to Next.js config. This option is not supported.',
});

delete options.generateLockfile;
Expand All @@ -166,11 +163,9 @@ function handlePropertiesFromTargetOptions(
delete options.experimentalAppOnly;
}

if ('experimentalBuildMode' in options) {
if ('experimentalBuildMode' in options && options.experimentalBuildMode) {
options['args'] ??= [];
options['args'].push(
`--experimental-build-mode ${options.experimentalBuildMode}`
);
options['args'].push(`--experimental-build-mode`);
delete options.experimentalBuildMode;
}

Expand Down
Loading

0 comments on commit 915eb74

Please sign in to comment.