@nx/rspack 24.0.0-pr.37405.acdaf31 → 24.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/module-federation.d.ts +6 -4
  2. package/dist/module-federation.js +25 -7
  3. package/dist/ready-check.d.ts +1 -0
  4. package/dist/ready-check.js +9 -0
  5. package/dist/ready-signal.d.ts +1 -0
  6. package/dist/ready-signal.js +5 -0
  7. package/dist/src/executors/dev-server/dev-server.impl.js +0 -2
  8. package/dist/src/executors/rspack/lib/config.js +18 -8
  9. package/dist/src/executors/ssr-dev-server/schema.json +2 -1
  10. package/dist/src/executors/ssr-dev-server/ssr-dev-server.impl.js +2 -0
  11. package/dist/src/generators/configuration/configuration.js +5 -29
  12. package/dist/src/generators/configuration/schema.json +2 -2
  13. package/dist/src/generators/convert-config-to-rspack-plugin/convert-config-to-rspack-plugin.js +96 -53
  14. package/dist/src/generators/convert-config-to-rspack-plugin/lib/extract-rspack-options.d.ts +2 -0
  15. package/dist/src/generators/convert-config-to-rspack-plugin/lib/extract-rspack-options.js +46 -2
  16. package/dist/src/generators/convert-config-to-rspack-plugin/schema.json +2 -2
  17. package/dist/src/generators/convert-to-inferred/convert-to-inferred.js +5 -4
  18. package/dist/src/generators/convert-to-inferred/utils/ast.d.ts +2 -0
  19. package/dist/src/generators/convert-to-inferred/utils/ast.js +13 -0
  20. package/dist/src/generators/convert-to-inferred/utils/build-post-target-transformer.js +25 -5
  21. package/dist/src/generators/convert-to-inferred/utils/serve-post-target-transformer.js +13 -14
  22. package/dist/src/generators/convert-webpack/convert-webpack.js +20 -74
  23. package/dist/src/generators/convert-webpack/lib/transform-plugin-config.d.ts +1 -1
  24. package/dist/src/generators/convert-webpack/lib/transform-plugin-config.js +47 -69
  25. package/dist/src/generators/init/init.js +38 -44
  26. package/dist/src/generators/init/schema.d.ts +0 -1
  27. package/dist/src/migrations/update-24-0-0/finish-inferred-conversion.md +11 -0
  28. package/dist/src/migrations/update-24-0-0/inventory.d.ts +10 -0
  29. package/dist/src/migrations/update-24-0-0/inventory.js +55 -0
  30. package/dist/src/migrations/update-24-0-0/migrate-compose-plugins.d.ts +10 -0
  31. package/dist/src/migrations/update-24-0-0/migrate-compose-plugins.js +68 -0
  32. package/dist/src/migrations/update-24-0-0/migrate-compose-plugins.md +95 -0
  33. package/dist/src/migrations/update-24-0-0/remove-deprecated-executors.d.ts +6 -0
  34. package/dist/src/migrations/update-24-0-0/remove-deprecated-executors.js +39 -0
  35. package/dist/src/migrations/update-24-0-0/remove-deprecated-executors.md +90 -0
  36. package/dist/src/plugins/nx-app-rspack-plugin/nx-app-rspack-plugin.d.ts +2 -0
  37. package/dist/src/plugins/nx-app-rspack-plugin/nx-app-rspack-plugin.js +10 -1
  38. package/dist/src/plugins/plugin.js +16 -0
  39. package/dist/src/plugins/utils/apply-base-config.js +1 -1
  40. package/dist/src/utils/config.d.ts +10 -14
  41. package/dist/src/utils/config.js +17 -70
  42. package/dist/src/utils/deprecation.d.ts +3 -6
  43. package/dist/src/utils/deprecation.js +10 -23
  44. package/dist/src/utils/dev-server-ready-check.d.ts +40 -0
  45. package/dist/src/utils/dev-server-ready-check.js +293 -0
  46. package/dist/src/utils/dev-server-ready-signal.d.ts +29 -0
  47. package/dist/src/utils/dev-server-ready-signal.js +51 -0
  48. package/dist/src/utils/e2e-web-server-info-utils.d.ts +1 -1
  49. package/dist/src/utils/e2e-web-server-info-utils.js +2 -2
  50. package/dist/src/utils/generator-utils.d.ts +1 -2
  51. package/dist/src/utils/generator-utils.js +69 -185
  52. package/dist/src/utils/read-rspack-options.d.ts +1 -1
  53. package/dist/src/utils/read-rspack-options.js +4 -4
  54. package/dist/src/utils/with-nx.d.ts +5 -9
  55. package/dist/src/utils/with-nx.js +5 -32
  56. package/dist/src/utils/with-react.d.ts +5 -8
  57. package/dist/src/utils/with-react.js +5 -15
  58. package/dist/src/utils/with-web.d.ts +5 -8
  59. package/dist/src/utils/with-web.js +5 -44
  60. package/executors.json +0 -25
  61. package/migrations.json +13 -0
  62. package/package.json +39 -10
  63. package/dist/src/executors/module-federation-dev-server/lib/index.d.ts +0 -2
  64. package/dist/src/executors/module-federation-dev-server/lib/index.js +0 -5
  65. package/dist/src/executors/module-federation-dev-server/lib/normalize-options.d.ts +0 -4
  66. package/dist/src/executors/module-federation-dev-server/lib/normalize-options.js +0 -19
  67. package/dist/src/executors/module-federation-dev-server/lib/start-remotes.d.ts +0 -5
  68. package/dist/src/executors/module-federation-dev-server/lib/start-remotes.js +0 -33
  69. package/dist/src/executors/module-federation-dev-server/module-federation-dev-server.impl.d.ts +0 -6
  70. package/dist/src/executors/module-federation-dev-server/module-federation-dev-server.impl.js +0 -74
  71. package/dist/src/executors/module-federation-dev-server/schema.d.ts +0 -25
  72. package/dist/src/executors/module-federation-dev-server/schema.json +0 -104
  73. package/dist/src/executors/module-federation-ssr-dev-server/lib/index.d.ts +0 -2
  74. package/dist/src/executors/module-federation-ssr-dev-server/lib/index.js +0 -5
  75. package/dist/src/executors/module-federation-ssr-dev-server/lib/normalize-options.d.ts +0 -4
  76. package/dist/src/executors/module-federation-ssr-dev-server/lib/normalize-options.js +0 -23
  77. package/dist/src/executors/module-federation-ssr-dev-server/lib/start-remotes.d.ts +0 -5
  78. package/dist/src/executors/module-federation-ssr-dev-server/lib/start-remotes.js +0 -34
  79. package/dist/src/executors/module-federation-ssr-dev-server/module-federation-ssr-dev-server.impl.d.ts +0 -5
  80. package/dist/src/executors/module-federation-ssr-dev-server/module-federation-ssr-dev-server.impl.js +0 -65
  81. package/dist/src/executors/module-federation-ssr-dev-server/schema.d.ts +0 -29
  82. package/dist/src/executors/module-federation-ssr-dev-server/schema.json +0 -85
  83. package/dist/src/executors/module-federation-static-server/module-federation-static-server.impl.d.ts +0 -12
  84. package/dist/src/executors/module-federation-static-server/module-federation-static-server.impl.js +0 -237
  85. package/dist/src/executors/module-federation-static-server/schema.d.ts +0 -3
  86. package/dist/src/executors/module-federation-static-server/schema.json +0 -16
  87. package/dist/src/executors/rspack/rspack.impl.d.ts +0 -7
  88. package/dist/src/executors/rspack/rspack.impl.js +0 -127
  89. package/dist/src/executors/rspack/schema.json +0 -410
  90. package/dist/src/generators/convert-webpack/lib/transform-cjs.d.ts +0 -2
  91. package/dist/src/generators/convert-webpack/lib/transform-cjs.js +0 -263
  92. package/dist/src/generators/convert-webpack/lib/transform-esm.d.ts +0 -2
  93. package/dist/src/generators/convert-webpack/lib/transform-esm.js +0 -263
  94. package/dist/src/utils/has-plugin.d.ts +0 -2
  95. package/dist/src/utils/has-plugin.js +0 -10
  96. package/dist/src/utils/module-federation-deprecation.d.ts +0 -6
  97. package/dist/src/utils/module-federation-deprecation.js +0 -30
@@ -1,4 +1,6 @@
1
- /**
2
- * @deprecated Use `@nx/module-federation/rspack` instead. This will be removed in Nx v22.
3
- */
4
- export { withModuleFederation, withModuleFederationForSSR, } from '@nx/module-federation/rspack';
1
+ type IdentityConfigFn = <T>(config: T, ...rest: unknown[]) => T;
2
+ /** @deprecated Removed in Nx v24. Use `ModuleFederationPlugin` from `@module-federation/enhanced`. This stub will be removed in Nx v25. */
3
+ export declare function withModuleFederation(..._args: unknown[]): Promise<IdentityConfigFn>;
4
+ /** @deprecated Removed in Nx v24. Use `ModuleFederationPlugin` from `@module-federation/enhanced`. This stub will be removed in Nx v25. */
5
+ export declare function withModuleFederationForSSR(..._args: unknown[]): Promise<IdentityConfigFn>;
6
+ export {};
@@ -1,9 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.withModuleFederationForSSR = exports.withModuleFederation = void 0;
4
- /**
5
- * @deprecated Use `@nx/module-federation/rspack` instead. This will be removed in Nx v22.
6
- */
7
- var rspack_1 = require("@nx/module-federation/rspack");
8
- Object.defineProperty(exports, "withModuleFederation", { enumerable: true, get: function () { return rspack_1.withModuleFederation; } });
9
- Object.defineProperty(exports, "withModuleFederationForSSR", { enumerable: true, get: function () { return rspack_1.withModuleFederationForSSR; } });
3
+ exports.withModuleFederation = withModuleFederation;
4
+ exports.withModuleFederationForSSR = withModuleFederationForSSR;
5
+ const devkit_1 = require("@nx/devkit");
6
+ // TODO(v25): Delete this subpath. It keeps 23.x configs loading during graph creation so `nx migrate` can run.
7
+ const REMOVED_MESSAGE = 'Nx Module Federation was removed in Nx v24. `@nx/rspack/module-federation` is a stub that keeps old configs loadable during project graph creation; it does not configure Module Federation. Follow https://nx.dev/docs/kb/migrate-from-nx-module-federation to move to the official Module Federation plugin.';
8
+ let warned = false;
9
+ // Graph creation only reads the config, so it keeps working; a build would silently drop federation.
10
+ function failOutsideGraphCreation() {
11
+ if (!global.NX_GRAPH_CREATION)
12
+ throw new Error(REMOVED_MESSAGE);
13
+ if (warned)
14
+ return;
15
+ warned = true;
16
+ devkit_1.logger.warn(REMOVED_MESSAGE);
17
+ }
18
+ /** @deprecated Removed in Nx v24. Use `ModuleFederationPlugin` from `@module-federation/enhanced`. This stub will be removed in Nx v25. */
19
+ async function withModuleFederation(..._args) {
20
+ failOutsideGraphCreation();
21
+ return (config) => config;
22
+ }
23
+ /** @deprecated Removed in Nx v24. Use `ModuleFederationPlugin` from `@module-federation/enhanced`. This stub will be removed in Nx v25. */
24
+ async function withModuleFederationForSSR(..._args) {
25
+ failOutsideGraphCreation();
26
+ return (config) => config;
27
+ }
@@ -0,0 +1 @@
1
+ export declare function waitForDevServer(configPath: string): Promise<void>;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.waitForDevServer = waitForDevServer;
4
+ const dev_server_ready_check_1 = require("./src/utils/dev-server-ready-check");
5
+ async function waitForDevServer(configPath) {
6
+ await (0, dev_server_ready_check_1.waitForRspackDevServer)(configPath);
7
+ // A config can leave handles open that would keep the check running
8
+ process.exit(0);
9
+ }
@@ -0,0 +1 @@
1
+ export { NxReadySignalPlugin } from './src/utils/dev-server-ready-signal';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NxReadySignalPlugin = void 0;
4
+ var dev_server_ready_signal_1 = require("./src/utils/dev-server-ready-signal");
5
+ Object.defineProperty(exports, "NxReadySignalPlugin", { enumerable: true, get: function () { return dev_server_ready_signal_1.NxReadySignalPlugin; } });
@@ -9,9 +9,7 @@ const create_compiler_1 = require("../../utils/create-compiler");
9
9
  const mode_utils_1 = require("../../utils/mode-utils");
10
10
  const normalize_options_1 = require("../rspack/lib/normalize-options");
11
11
  const get_dev_server_config_1 = require("./lib/get-dev-server-config");
12
- const deprecation_1 = require("../../utils/deprecation");
13
12
  async function* runExecutor(options, context) {
14
- (0, deprecation_1.warnRspackDevServerExecutorDeprecation)();
15
13
  process.env.NODE_ENV ??= options.mode ?? 'development';
16
14
  if ((0, mode_utils_1.isMode)(process.env.NODE_ENV)) {
17
15
  options.mode = process.env.NODE_ENV;
@@ -2,10 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getRspackConfigs = getRspackConfigs;
4
4
  const config_1 = require("../../../utils/config");
5
- const deprecation_1 = require("../../../utils/deprecation");
6
5
  const resolve_user_defined_rspack_config_1 = require("../../../utils/resolve-user-defined-rspack-config");
7
- const with_nx_1 = require("../../../utils/with-nx");
8
- const with_web_1 = require("../../../utils/with-web");
6
+ const apply_base_config_1 = require("../../../plugins/utils/apply-base-config");
7
+ const apply_web_config_1 = require("../../../plugins/utils/apply-web-config");
9
8
  async function getRspackConfigs(options, context) {
10
9
  let maybeUserDefinedConfig = await (0, resolve_user_defined_rspack_config_1.resolveUserDefinedRspackConfig)(options.rspackConfig, options.tsConfig);
11
10
  let userDefinedConfig = 'default' in maybeUserDefinedConfig
@@ -16,11 +15,22 @@ async function getRspackConfigs(options, context) {
16
15
  if (typeof userDefinedConfig.then === 'function') {
17
16
  userDefinedConfig = await userDefinedConfig;
18
17
  }
19
- // Nx composes these helpers internally to build the default config; suppress
20
- // their deprecation warning so it fires only for user-authored configs.
21
- const config = await (0, deprecation_1.suppressRspackComposeHelperWarnings)(() => (options.target === 'web'
22
- ? (0, config_1.composePlugins)((0, with_nx_1.withNx)(options), (0, with_web_1.withWeb)(options))
23
- : (0, with_nx_1.withNx)(options))({}, { options, context }));
18
+ const config = {};
19
+ const configOptions = {
20
+ ...options,
21
+ target: options.target ?? 'web',
22
+ assets: options.assets ?? [],
23
+ root: context.root,
24
+ projectName: context.projectName,
25
+ targetName: context.targetName,
26
+ configurationName: context.configurationName,
27
+ projectGraph: context.projectGraph,
28
+ useLegacyHtmlPlugin: false,
29
+ };
30
+ (0, apply_base_config_1.applyBaseConfig)(configOptions, config);
31
+ if (options.target === 'web') {
32
+ (0, apply_web_config_1.applyWebConfig)(configOptions, config);
33
+ }
24
34
  if (typeof userDefinedConfig === 'function' &&
25
35
  ((0, config_1.isNxRspackComposablePlugin)(userDefinedConfig) ||
26
36
  !options.standardRspackConfigFunction)) {
@@ -5,6 +5,7 @@
5
5
  "description": "Serve a SSR application using rspack.",
6
6
  "cli": "nx",
7
7
  "type": "object",
8
+ "x-deprecated": "The `@nx/rspack:ssr-dev-server` executor is deprecated and will be removed in Nx v25. Run the server from source with the `@nx/js/tsx` plugin, with the browser build in watch mode as a continuous dependency. See https://nx.dev/docs/kb/replace-ssr-dev-server.",
8
9
  "properties": {
9
10
  "browserTarget": {
10
11
  "type": "string",
@@ -18,7 +19,7 @@
18
19
  },
19
20
  "port": {
20
21
  "type": "number",
21
- "description": "The port to be set on `process.env.PORT` for use in the server.",
22
+ "description": "The port the server application listens on. The executor waits for it to accept connections before reporting the server as ready.",
22
23
  "default": 4200,
23
24
  "x-priority": "important"
24
25
  },
@@ -5,8 +5,10 @@ const tslib_1 = require("tslib");
5
5
  const internal_1 = require("@nx/devkit/internal");
6
6
  const devkit_1 = require("@nx/devkit");
7
7
  const pc = tslib_1.__importStar(require("picocolors"));
8
+ const deprecation_1 = require("../../utils/deprecation");
8
9
  const wait_until_server_is_listening_1 = require("./lib/wait-until-server-is-listening");
9
10
  async function* ssrDevServerExecutor(options, context) {
11
+ (0, deprecation_1.warnRspackSsrDevServerExecutorDeprecation)();
10
12
  const browserTarget = (0, devkit_1.parseTargetString)(options.browserTarget, context.projectGraph);
11
13
  const serverTarget = (0, devkit_1.parseTargetString)(options.serverTarget, context);
12
14
  const browserOptions = (0, devkit_1.readTargetOptions)(browserTarget, context);
@@ -7,7 +7,6 @@ const path_1 = require("path");
7
7
  const generator_utils_1 = require("../../utils/generator-utils");
8
8
  const init_1 = tslib_1.__importDefault(require("../init/init"));
9
9
  const internal_1 = require("@nx/js/internal");
10
- const deprecation_1 = require("../../utils/deprecation");
11
10
  const assert_supported_rspack_version_1 = require("../../utils/assert-supported-rspack-version");
12
11
  function projectIsRootProjectInStandaloneWorkspace(projectRoot) {
13
12
  return (0, path_1.relative)(devkit_1.workspaceRoot, projectRoot).length === 0;
@@ -49,36 +48,28 @@ async function configurationGenerator(tree, options) {
49
48
  const task = await (0, init_1.default)(tree, {
50
49
  ...options,
51
50
  });
52
- const { targets, root, projectType } = (0, devkit_1.readProjectConfiguration)(tree, options.project);
51
+ const { targets, root } = (0, devkit_1.readProjectConfiguration)(tree, options.project);
53
52
  const { target, framework } = (0, generator_utils_1.determineFrameworkAndTarget)(tree, options, root, targets);
54
53
  options.framework = framework;
55
54
  options.target = target;
56
55
  let foundStylePreprocessorOptions;
57
56
  let buildTargetName = 'build';
58
57
  let serveTargetName = 'serve';
59
- /**
60
- * This is for when we are converting an existing project
61
- * to use the vite executors.
62
- */
63
- let projectAlreadyHasRspackTargets = {};
64
58
  if (!options.newProject) {
65
59
  const userProvidedTargetName = {
66
60
  build: options.buildTarget,
67
61
  serve: options.serveTarget,
68
62
  };
69
63
  const { validFoundTargetName, projectContainsUnsupportedExecutor, userProvidedTargetIsUnsupported, alreadyHasNxRspackTargets, } = (0, generator_utils_1.findExistingTargetsInProject)(targets, userProvidedTargetName);
70
- projectAlreadyHasRspackTargets = alreadyHasNxRspackTargets;
71
- if (alreadyHasNxRspackTargets.build &&
72
- (alreadyHasNxRspackTargets.serve ||
73
- (0, internal_1.getProjectType)(tree, options.project, projectType) === 'library' ||
74
- options.framework === 'nest')) {
75
- throw new Error(`The project ${options.project} is already configured to use the @nx/rspack executors.
64
+ if (alreadyHasNxRspackTargets.build || alreadyHasNxRspackTargets.serve) {
65
+ throw new Error(`The project ${options.project} has targets using the removed @nx/rspack executors.
76
66
  Please try a different project, or remove the existing targets
77
67
  and re-run this generator to reset the existing Rspack Configuration.
78
68
  `);
79
69
  }
70
+ (0, generator_utils_1.assertNoRemovedExecutorTargets)(options.project, targets);
80
71
  if (!validFoundTargetName.build && projectContainsUnsupportedExecutor) {
81
- throw new Error(`The project ${options.project} cannot be converted to use the @nx/rspack executors.`);
72
+ throw new Error(`The project ${options.project} cannot be converted to use Rspack.`);
82
73
  }
83
74
  if (!projectContainsUnsupportedExecutor &&
84
75
  !validFoundTargetName.build &&
@@ -100,21 +91,6 @@ async function configurationGenerator(tree, options) {
100
91
  (0, generator_utils_1.deleteWebpackConfig)(tree, root, targets?.[buildTargetName]?.options?.webpackConfig);
101
92
  editTsConfig(tree, root, options.framework, (0, devkit_1.joinPathFragments)((0, devkit_1.offsetFromRoot)(root), 'tsconfig.base.json'));
102
93
  }
103
- const willScaffoldExecutorTargets = !projectAlreadyHasRspackTargets.build ||
104
- ((options.framework !== 'none' || options.devServer) &&
105
- options.framework !== 'nest' &&
106
- !projectAlreadyHasRspackTargets.serve);
107
- if (willScaffoldExecutorTargets) {
108
- (0, deprecation_1.warnRspackExecutorGenerating)();
109
- }
110
- if (!projectAlreadyHasRspackTargets.build) {
111
- (0, generator_utils_1.addOrChangeBuildTarget)(tree, options, buildTargetName);
112
- }
113
- if ((options.framework !== 'none' || options.devServer) &&
114
- options.framework !== 'nest' &&
115
- !projectAlreadyHasRspackTargets.serve) {
116
- (0, generator_utils_1.addOrChangeServeTarget)(tree, options, serveTargetName);
117
- }
118
94
  (0, generator_utils_1.writeRspackConfigFile)(tree, options, foundStylePreprocessorOptions);
119
95
  await (0, devkit_1.formatFiles)(tree);
120
96
  return task;
@@ -58,11 +58,11 @@
58
58
  },
59
59
  "buildTarget": {
60
60
  "type": "string",
61
- "description": "The build target of the project to be transformed to use the @nx/vite:build executor."
61
+ "description": "The existing build target of the project to convert to Rspack."
62
62
  },
63
63
  "serveTarget": {
64
64
  "type": "string",
65
- "description": "The serve target of the project to be transformed to use the @nx/vite:dev-server and @nx/vite:preview-server executors."
65
+ "description": "The existing serve target of the project, used to check that it can be converted to Rspack."
66
66
  },
67
67
  "rootProject": {
68
68
  "type": "boolean",
@@ -8,6 +8,7 @@ const normalize_path_options_1 = require("./lib/normalize-path-options");
8
8
  const path_1 = require("path");
9
9
  const validate_project_1 = require("./lib/validate-project");
10
10
  const assert_supported_rspack_version_1 = require("../../utils/assert-supported-rspack-version");
11
+ const buildExecutors = ['@nx/rspack:rspack', '@nrwl/rspack:rspack'];
11
12
  // Make text JSON compatible
12
13
  const preprocessText = (text) => {
13
14
  return text
@@ -20,66 +21,44 @@ async function convertConfigToRspackPluginGenerator(tree, options) {
20
21
  (0, assert_supported_rspack_version_1.assertSupportedRspackVersion)(tree);
21
22
  let migrated = 0;
22
23
  const projects = (0, devkit_1.getProjects)(tree);
23
- (0, internal_1.forEachExecutorOptions)(tree, '@nx/rspack:rspack', (currentTargetOptions, projectName, targetName, configurationName) => {
24
- if (options.project && projectName !== options.project) {
25
- return;
26
- }
27
- if (!configurationName) {
28
- const project = projects.get(projectName);
29
- const target = project.targets[targetName];
30
- const hasError = (0, validate_project_1.validateProject)(tree, project);
31
- if (hasError) {
32
- throw new Error(hasError);
24
+ for (const executor of buildExecutors) {
25
+ (0, internal_1.forEachExecutorOptions)(tree, executor, (currentTargetOptions, projectName, targetName, configurationName) => {
26
+ if (options.project && projectName !== options.project) {
27
+ return;
33
28
  }
34
- const rspackConfigPath = currentTargetOptions?.rspackConfig || '';
35
- if (rspackConfigPath && tree.exists(rspackConfigPath)) {
36
- let { withNxConfig: rspackOptions, withReactConfig } = (0, extract_rspack_options_1.extractRspackOptions)(tree, rspackConfigPath);
37
- // if rspackOptions === undefined
38
- // withNx was not found in the rspack.config.js file so we should skip this project
39
- if (rspackOptions !== undefined) {
40
- let parsedOptions = {};
41
- if (rspackOptions) {
42
- parsedOptions = JSON.parse(preprocessText(rspackOptions.getText()));
43
- parsedOptions = (0, normalize_path_options_1.normalizePathOptions)(project.root, parsedOptions);
44
- }
29
+ if (!configurationName) {
30
+ const project = projects.get(projectName);
31
+ const target = project.targets[targetName];
32
+ const hasError = (0, validate_project_1.validateProject)(tree, project);
33
+ if (hasError) {
34
+ throw new Error(hasError);
35
+ }
36
+ const rspackConfigPath = currentTargetOptions?.rspackConfig || '';
37
+ if (rspackConfigPath &&
38
+ tree.exists(rspackConfigPath) &&
39
+ convertConfigFile(tree, project.root, rspackConfigPath)) {
45
40
  target.options.standardRspackConfigFunction = true;
46
41
  (0, devkit_1.updateProjectConfiguration)(tree, projectName, project);
47
- const { dir, name, ext } = (0, path_1.parse)(rspackConfigPath);
48
- tree.rename(rspackConfigPath, `${(0, devkit_1.joinPathFragments)(dir, `${name}.old${ext}`)}`);
49
- tree.write(rspackConfigPath, (0, devkit_1.stripIndents) `
50
- const { NxAppRspackPlugin } = require('@nx/rspack/app-plugin');
51
- const { NxReactRspackPlugin } = require('@nx/rspack/react-plugin');
52
- const { useLegacyNxPlugin } = require('@nx/rspack');
53
-
54
- // This file was migrated using @nx/rspack:convert-config-to-rspack-plugin from your './rspack.config.old.js'
55
- // Please check that the options here are correct as they were moved from the old rspack.config.js to this file.
56
- const options = ${rspackOptions ? JSON.stringify(parsedOptions, null, 2) : '{}'};
57
-
58
- /**
59
- * @type{import('@rspack/core').RspackOptionsNormalized}
60
- */
61
- module.exports = async () => ({
62
- plugins: [
63
- ${rspackOptions
64
- ? 'new NxAppRspackPlugin(options)'
65
- : 'new NxAppRspackPlugin()'},
66
- ${withReactConfig
67
- ? `new NxReactRspackPlugin(${withReactConfig.getText()})`
68
- : `new NxReactRspackPlugin()`},
69
- // NOTE: useLegacyNxPlugin ensures that the non-standard Rspack configuration file previously used still works.
70
- // To remove its usage, move options such as "plugins" into this file as standard Rspack configuration options.
71
- // To enhance configurations after Nx plugins have applied, you can add a new plugin with the \`apply\` method.
72
- // e.g. \`{ apply: (compiler) => { /* modify compiler.options */ }\`
73
- // eslint-disable-next-line react-hooks/rules-of-hooks
74
- await useLegacyNxPlugin(require('./rspack.config.old'), options),
75
- ],
76
- });
77
- `);
78
42
  migrated++;
79
43
  }
80
44
  }
45
+ });
46
+ }
47
+ // Projects already on the inference plugin keep their options in the config,
48
+ // so only the config needs converting.
49
+ for (const [projectName, project] of projects) {
50
+ if (options.project && projectName !== options.project) {
51
+ continue;
52
+ }
53
+ if (Object.values(project.targets ?? {}).some((target) => buildExecutors.includes(target.executor))) {
54
+ continue;
81
55
  }
82
- });
56
+ const rspackConfigPath = (0, devkit_1.joinPathFragments)(project.root, 'rspack.config.js');
57
+ if (tree.exists(rspackConfigPath) &&
58
+ convertConfigFile(tree, project.root, rspackConfigPath)) {
59
+ migrated++;
60
+ }
61
+ }
83
62
  if (migrated === 0) {
84
63
  throw new Error('Could not find any projects to migrate.');
85
64
  }
@@ -87,4 +66,68 @@ async function convertConfigToRspackPluginGenerator(tree, options) {
87
66
  await (0, devkit_1.formatFiles)(tree);
88
67
  }
89
68
  }
69
+ /** Returns whether the config used `withNx` and was converted. */
70
+ function convertConfigFile(tree, projectRoot, rspackConfigPath) {
71
+ let { withNxConfig: rspackOptions, withReactConfig, strippedSource, leftoverHelpers, } = (0, extract_rspack_options_1.extractRspackOptions)(tree, rspackConfigPath);
72
+ // if rspackOptions === undefined
73
+ // withNx was not found in the rspack.config.js file so we should skip this project
74
+ if (rspackOptions !== undefined) {
75
+ // The `.old` config would call helpers whose imports were removed, or inert stubs.
76
+ if (leftoverHelpers.length) {
77
+ throw new Error(`Could not convert ${rspackConfigPath}: ${leftoverHelpers.join(', ')} would be left in the old config. Only \`require\`d helpers passed directly to \`composePlugins\` are supported.`);
78
+ }
79
+ let parsedOptions = {};
80
+ if (rspackOptions) {
81
+ // Parse before writing anything: a non-literal option value leaves the
82
+ // project untouched for the migration prompt instead of a config whose
83
+ // helper calls are gone and whose options never made it across.
84
+ try {
85
+ parsedOptions = JSON.parse(preprocessText(rspackOptions.getText()));
86
+ }
87
+ catch {
88
+ throw new Error(`Could not read the \`withNx\` options in ${rspackConfigPath}. They must be a plain object literal; spreads, variables and function calls are not supported.`);
89
+ }
90
+ parsedOptions = (0, normalize_path_options_1.normalizePathOptions)(projectRoot, parsedOptions);
91
+ }
92
+ if (strippedSource !== undefined) {
93
+ tree.write(rspackConfigPath, strippedSource);
94
+ }
95
+ const { dir, name, ext } = (0, path_1.parse)(rspackConfigPath);
96
+ tree.rename(rspackConfigPath, `${(0, devkit_1.joinPathFragments)(dir, `${name}.old${ext}`)}`);
97
+ const usesReact = withReactConfig !== undefined;
98
+ const reactRequire = usesReact
99
+ ? `\nconst { NxReactRspackPlugin } = require('@nx/rspack/react-plugin');`
100
+ : '';
101
+ const reactPlugin = usesReact
102
+ ? `\nnew NxReactRspackPlugin(${withReactConfig ? withReactConfig.getText() : ''}),`
103
+ : '';
104
+ tree.write(rspackConfigPath, (0, devkit_1.stripIndents) `
105
+ const { NxAppRspackPlugin } = require('@nx/rspack/app-plugin');${reactRequire}
106
+ const { useLegacyNxPlugin } = require('@nx/rspack');
107
+
108
+ // This file was migrated using @nx/rspack:convert-config-to-rspack-plugin from your './rspack.config.old.js'
109
+ // Please check that the options here are correct as they were moved from the old rspack.config.js to this file.
110
+ const options = ${rspackOptions ? JSON.stringify(parsedOptions, null, 2) : '{}'};
111
+
112
+ /**
113
+ * @type{import('@rspack/core').RspackOptionsNormalized}
114
+ */
115
+ module.exports = async () => ({
116
+ plugins: [
117
+ ${rspackOptions
118
+ ? 'new NxAppRspackPlugin(options)'
119
+ : 'new NxAppRspackPlugin()'},${reactPlugin}
120
+ // NOTE: useLegacyNxPlugin ensures that the non-standard Rspack configuration file previously used still works.
121
+ // To remove its usage, move options such as "plugins" into this file as standard Rspack configuration options.
122
+ // To enhance configurations after Nx plugins have applied, you can add a new plugin with the \`apply\` method.
123
+ // e.g. \`{ apply: (compiler) => { /* modify compiler.options */ }\`
124
+ // eslint-disable-next-line react-hooks/rules-of-hooks
125
+ await useLegacyNxPlugin(require('./rspack.config.old'), options),
126
+ ],
127
+ });
128
+ `);
129
+ return true;
130
+ }
131
+ return false;
132
+ }
90
133
  exports.default = convertConfigToRspackPluginGenerator;
@@ -3,4 +3,6 @@ import * as ts from 'typescript';
3
3
  export declare function extractRspackOptions(tree: Tree, rspackConfigPath: string): {
4
4
  withNxConfig: "" | ts.Node;
5
5
  withReactConfig: "" | ts.Node;
6
+ strippedSource: string;
7
+ leftoverHelpers: string[];
6
8
  };
@@ -15,6 +15,10 @@ function extractRspackOptions(tree, rspackConfigPath) {
15
15
  const withWebCall = (0, tsquery_1.query)(sourceFile, withWebQuery);
16
16
  // If the config is empty set to empty string to avoid undefined. Undefined is used to check if the withNx exists inside of the config file.
17
17
  let withNxConfig, withReactConfig;
18
+ // Returned rather than written here so the caller can reject configs whose
19
+ // options are not a plain literal before touching the file.
20
+ let strippedSource;
21
+ let leftoverHelpers = [];
18
22
  withWebCall.forEach((node) => {
19
23
  const argument = node.arguments[0] || '';
20
24
  withNxConfig = argument; // Since withWeb and withNx use the same config object and both should not exist in the same file, we can reuse the withNxConfig variable.
@@ -37,9 +41,49 @@ function extractRspackOptions(tree, rspackConfigPath) {
37
41
  updatedSource = removeImportDeclarations(updatedSource, 'withNx', '@nx/rspack');
38
42
  updatedSource = removeImportDeclarations(updatedSource, 'withWeb', '@nx/rspack');
39
43
  updatedSource = removeImportDeclarations(updatedSource, 'withReact', '@nx/rspack');
40
- tree.write(rspackConfigPath, updatedSource);
44
+ updatedSource = inlineComposePlugins(updatedSource);
45
+ updatedSource = removeImportDeclarations(updatedSource, 'composePlugins', '@nx/rspack');
46
+ strippedSource = updatedSource;
47
+ leftoverHelpers = findHelperReferences(updatedSource);
41
48
  }
42
- return { withNxConfig, withReactConfig };
49
+ return { withNxConfig, withReactConfig, strippedSource, leftoverHelpers };
50
+ }
51
+ const REMOVED_HELPERS = new Set([
52
+ 'composePlugins',
53
+ 'composePluginsSync',
54
+ 'withNx',
55
+ 'withWeb',
56
+ 'withReact',
57
+ ]);
58
+ function findHelperReferences(source) {
59
+ const names = (0, tsquery_1.query)((0, tsquery_1.ast)(source), 'Identifier')
60
+ .map((node) => node.text)
61
+ .filter((name) => REMOVED_HELPERS.has(name));
62
+ return [...new Set(names)];
63
+ }
64
+ // `composePlugins` is an inert stub since Nx v24, so the old config composes its
65
+ // remaining callbacks with a local copy.
66
+ function inlineComposePlugins(source) {
67
+ let found = false;
68
+ const updatedSource = (0, tsquery_1.replace)(source, 'CallExpression > Identifier[name="composePlugins"]', (node) => {
69
+ if (node.parent.expression !== node) {
70
+ return node.getText();
71
+ }
72
+ found = true;
73
+ return 'composeLegacyPlugins';
74
+ });
75
+ if (!found)
76
+ return source;
77
+ return `${updatedSource}
78
+ function composeLegacyPlugins(...plugins) {
79
+ return async (config, ctx) => {
80
+ for (const plugin of plugins) {
81
+ config = await (await plugin)(config, ctx);
82
+ }
83
+ return config;
84
+ };
85
+ }
86
+ `;
43
87
  }
44
88
  function removeCallExpressions(source, functionNames) {
45
89
  let modifiedSource = source;
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/schema",
3
3
  "$id": "NxRspackConvertConfigToRspackPlugin",
4
- "description": "Convert existing Rspack project(s) using `@nx/rspack:rspack` executor that uses `withNx` to use `NxAppRspackPlugin`. Defaults to migrating all projects. Pass '--project' to migrate only one target.",
4
+ "description": "Convert existing Rspack config(s) that use `withNx` to use `NxAppRspackPlugin`, for projects on the `@nx/rspack:rspack` executor or the `@nx/rspack/plugin` inference plugin. Defaults to migrating all projects. Pass '--project' to migrate only one target.",
5
5
  "title": "Convert Rspack project using withNx to NxAppRspackPlugin",
6
6
  "type": "object",
7
7
  "properties": {
8
8
  "project": {
9
9
  "type": "string",
10
- "description": "The project to convert from using the `@nx/rspack:rspack` executor and `withNx` plugin to use `NxAppRspackPlugin`.",
10
+ "description": "The project whose rspack config to convert from the `withNx` plugin to `NxAppRspackPlugin`.",
11
11
  "x-priority": "important"
12
12
  },
13
13
  "skipFormat": {
@@ -41,7 +41,7 @@ async function convertToInferred(tree, options) {
41
41
  const convertMessage = [...logger.loggedMessages.values()]
42
42
  .flat()
43
43
  .find((v) => v.includes('@nx/rspack:convert-config-to-rspack-plugin'));
44
- if (convertMessage.length > 0) {
44
+ if (convertMessage?.length > 0) {
45
45
  logger.flushLogs((message) => !convertMessage.includes(message));
46
46
  throw new Error(convertMessage);
47
47
  }
@@ -63,9 +63,10 @@ async function convertToInferred(tree, options) {
63
63
  if (!options.skipFormat) {
64
64
  await (0, devkit_1.formatFiles)(tree);
65
65
  }
66
- return (0, devkit_1.runTasksInSerial)(installCallback, () => {
67
- migrationContext.logger.flushLogs();
68
- });
66
+ // Flushed now rather than in the callback so remove-deprecated-executors, which
67
+ // skips the install callback, still prints these.
68
+ migrationContext.logger.flushLogs();
69
+ return installCallback;
69
70
  }
70
71
  function skipProjectFilterFactory(tree) {
71
72
  return function skipProjectFilter(projectConfiguration) {
@@ -1,3 +1,5 @@
1
1
  import * as ts from 'typescript';
2
2
  export declare function toPropertyAssignment(key: string, value: unknown): ts.PropertyAssignment;
3
3
  export declare function toExpression(value: unknown): ts.Expression;
4
+ /** Whether a top-level `configValues` object written by convert-to-inferred has `key`. */
5
+ export declare function hasMigratedConfigValues(sourceFile: ts.SourceFile, key: string): boolean;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toPropertyAssignment = toPropertyAssignment;
4
4
  exports.toExpression = toExpression;
5
+ exports.hasMigratedConfigValues = hasMigratedConfigValues;
5
6
  const tslib_1 = require("tslib");
6
7
  const ts = tslib_1.__importStar(require("typescript"));
7
8
  function toPropertyAssignment(key, value) {
@@ -38,3 +39,15 @@ function toExpression(value) {
38
39
  return ts.factory.createObjectLiteralExpression(Object.entries(value).map(([key, value]) => toPropertyAssignment(key, value)));
39
40
  }
40
41
  }
42
+ /** Whether a top-level `configValues` object written by convert-to-inferred has `key`. */
43
+ function hasMigratedConfigValues(sourceFile, key) {
44
+ return sourceFile.statements.some((statement) => ts.isVariableStatement(statement) &&
45
+ statement.declarationList.declarations.some((declaration) => ts.isIdentifier(declaration.name) &&
46
+ declaration.name.text === 'configValues' &&
47
+ declaration.initializer !== undefined &&
48
+ ts.isObjectLiteralExpression(declaration.initializer) &&
49
+ declaration.initializer.properties.some((property) => ts.isPropertyAssignment(property) &&
50
+ (ts.isIdentifier(property.name) ||
51
+ ts.isStringLiteral(property.name)) &&
52
+ property.name.text === key)));
53
+ }
@@ -13,6 +13,13 @@ function buildPostTargetTransformerFactory(migrationContext) {
13
13
  projectName: projectDetails.projectName,
14
14
  projectRoot: projectDetails.root,
15
15
  };
16
+ // outputPath moves into the config, where `{options.outputPath}` can't resolve.
17
+ const outputPath = target.options?.outputPath;
18
+ if (target.outputs && typeof outputPath === 'string') {
19
+ target.outputs = target.outputs.map((output) => output.startsWith('{options.outputPath}')
20
+ ? output.replace('{options.outputPath}', `{workspaceRoot}/${outputPath}`)
21
+ : output.replace('{options.outputPath}', outputPath));
22
+ }
16
23
  const { pluginOptions, rspackConfigPath } = processOptions(target, context);
17
24
  updateRspackConfig(tree, rspackConfigPath, pluginOptions);
18
25
  if (target.outputs) {
@@ -108,6 +115,11 @@ function updateRspackConfig(tree, rspackConfig, pluginOptions) {
108
115
  sourceFile = (0, tsquery_1.ast)(rspackConfigText);
109
116
  };
110
117
  updateSources();
118
+ // A target kept on its executor is converted again on rerun, and its options
119
+ // are already in the config.
120
+ if ((0, ast_1.hasMigratedConfigValues)(sourceFile, 'build')) {
121
+ return;
122
+ }
111
123
  setOptionsInRspackConfig(tree, rspackConfigText, sourceFile, rspackConfig, pluginOptions);
112
124
  updateSources();
113
125
  setOptionsInNxRspackPlugin(tree, rspackConfigText, sourceFile, rspackConfig);
@@ -117,9 +129,17 @@ function updateRspackConfig(tree, rspackConfig, pluginOptions) {
117
129
  function setOptionsInRspackConfig(tree, text, sourceFile, rspackConfig, pluginOptions) {
118
130
  const { default: defaultOptions, ...configurationOptions } = pluginOptions;
119
131
  const optionsSelector = 'VariableStatement:has(VariableDeclaration:has(Identifier[name=options]))';
120
- const optionsVariable = (0, tsquery_1.query)(sourceFile, optionsSelector)[0];
121
- // This is assuming the `options` variable will be available since it's what the
122
- // `convert-config-to-rspack-plugin` generates
132
+ let optionsVariable = (0, tsquery_1.query)(sourceFile, optionsSelector)[0];
133
+ if (!optionsVariable) {
134
+ const plugin = (0, tsquery_1.query)(sourceFile, 'NewExpression:has(Identifier[name=NxAppRspackPlugin])')[0];
135
+ const argument = plugin.arguments?.[0];
136
+ if (argument && !ts.isObjectLiteralExpression(argument)) {
137
+ throw new Error('Move NxAppRspackPlugin options into an object literal before converting this config.');
138
+ }
139
+ text = `const options = ${argument?.getText(sourceFile) ?? '{}'};\n${text}`;
140
+ sourceFile = (0, tsquery_1.ast)(text);
141
+ optionsVariable = (0, tsquery_1.query)(sourceFile, optionsSelector)[0];
142
+ }
123
143
  let defaultOptionsObject;
124
144
  const optionsObject = (0, tsquery_1.query)(optionsVariable, 'ObjectLiteralExpression')[0];
125
145
  if (optionsObject.properties.length === 0) {
@@ -187,8 +207,8 @@ function setOptionsInNxRspackPlugin(tree, text, sourceFile, rspackConfig) {
187
207
  function setOptionsInLegacyNxPlugin(tree, text, sourceFile, rspackConfig) {
188
208
  const legacyNxPluginSelector = 'AwaitExpression CallExpression:has(Identifier[name=useLegacyNxPlugin])';
189
209
  const legacyNxPlugin = (0, tsquery_1.query)(sourceFile, legacyNxPluginSelector)[0];
190
- // we're assuming the `useLegacyNxPlugin` function is being called since it's what the `convert-config-to-rspack-plugin` generates
191
- // we've already "ensured" that the `convert-config-to-rspack-plugin` was run by checking for the `NxAppRspackPlugin` in the project validation
210
+ if (!legacyNxPlugin)
211
+ return;
192
212
  const updatedLegacyNxPlugin = ts.factory.updateCallExpression(legacyNxPlugin, legacyNxPlugin.expression, undefined, [legacyNxPlugin.arguments[0], ts.factory.createIdentifier('buildOptions')]);
193
213
  text = `${text.slice(0, legacyNxPlugin.getStart())}${ts
194
214
  .createPrinter()