@nx/vite 24.0.0-beta.2 → 24.0.0-beta.4

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 (74) hide show
  1. package/dist/executors.d.ts +0 -3
  2. package/dist/executors.js +0 -7
  3. package/dist/plugins/nx-copy-assets.plugin.d.ts +4 -5
  4. package/dist/plugins/nx-copy-assets.plugin.js +5 -49
  5. package/dist/plugins/nx-ready-signal.plugin.d.ts +8 -0
  6. package/dist/plugins/nx-ready-signal.plugin.js +41 -0
  7. package/dist/plugins/nx-tsconfig-paths.plugin.d.ts +5 -7
  8. package/dist/plugins/nx-tsconfig-paths.plugin.js +6 -247
  9. package/dist/ready-check.d.ts +1 -0
  10. package/dist/ready-check.js +9 -0
  11. package/dist/src/generators/configuration/configuration.js +2 -39
  12. package/dist/src/generators/configuration/lib/convert-non-vite.js +1 -0
  13. package/dist/src/generators/configuration/schema.d.ts +0 -1
  14. package/dist/src/generators/convert-to-inferred/lib/build-post-target-transformer.d.ts +0 -1
  15. package/dist/src/generators/convert-to-inferred/lib/build-post-target-transformer.js +3 -66
  16. package/dist/src/generators/init/init.js +20 -32
  17. package/dist/src/generators/init/schema.d.ts +0 -1
  18. package/dist/src/generators/init/schema.json +1 -1
  19. package/dist/src/generators/setup-paths-plugin/schema.d.ts +0 -1
  20. package/dist/src/generators/setup-paths-plugin/schema.json +2 -2
  21. package/dist/src/generators/setup-paths-plugin/setup-paths-plugin.js +16 -91
  22. package/dist/src/migrations/update-23-0-0/ai-instructions-for-vitest-3.md +5 -5
  23. package/dist/src/migrations/update-23-0-0/ai-instructions-for-vitest-4.md +6 -6
  24. package/dist/src/migrations/update-24-0-0/finish-inferred-conversion.md +12 -0
  25. package/dist/src/migrations/update-24-0-0/migrate-config-helpers.md +86 -0
  26. package/dist/src/migrations/update-24-0-0/migrate-nx-vite-ts-paths.d.ts +2 -0
  27. package/dist/src/migrations/update-24-0-0/migrate-nx-vite-ts-paths.js +154 -0
  28. package/dist/src/migrations/update-24-0-0/register-typescript-plugin-for-typecheck.d.ts +4 -0
  29. package/dist/src/migrations/update-24-0-0/register-typescript-plugin-for-typecheck.js +11 -0
  30. package/dist/src/migrations/update-24-0-0/register-typescript-plugin-for-typecheck.md +37 -0
  31. package/dist/src/migrations/update-24-0-0/remove-deprecated-executors.d.ts +6 -0
  32. package/dist/src/migrations/update-24-0-0/remove-deprecated-executors.js +46 -0
  33. package/dist/src/migrations/update-24-0-0/remove-deprecated-executors.md +71 -0
  34. package/dist/src/plugins/plugin.d.ts +9 -5
  35. package/dist/src/plugins/plugin.js +56 -49
  36. package/dist/src/utils/deprecation.d.ts +2 -9
  37. package/dist/src/utils/deprecation.js +5 -35
  38. package/dist/src/utils/dev-server-ready-check.d.ts +27 -0
  39. package/dist/src/utils/dev-server-ready-check.js +174 -0
  40. package/dist/src/utils/e2e-web-server-info-utils.d.ts +2 -2
  41. package/dist/src/utils/e2e-web-server-info-utils.js +4 -4
  42. package/dist/src/utils/executor-utils.d.ts +0 -10
  43. package/dist/src/utils/executor-utils.js +0 -51
  44. package/dist/src/utils/generator-utils.d.ts +1 -10
  45. package/dist/src/utils/generator-utils.js +62 -114
  46. package/dist/src/utils/options-utils.d.ts +0 -16
  47. package/dist/src/utils/options-utils.js +0 -73
  48. package/dist/src/utils/versions.d.ts +2 -0
  49. package/dist/src/utils/versions.js +3 -1
  50. package/dist/src/utils/vite-config-edit-utils.d.ts +9 -1
  51. package/dist/src/utils/vite-config-edit-utils.js +143 -1
  52. package/executors.json +2 -34
  53. package/generators.json +1 -1
  54. package/migrations.json +19 -0
  55. package/package.json +22 -7
  56. package/dist/src/executors/build/build.impl.d.ts +0 -11
  57. package/dist/src/executors/build/build.impl.js +0 -205
  58. package/dist/src/executors/build/compat.d.ts +0 -2
  59. package/dist/src/executors/build/compat.js +0 -6
  60. package/dist/src/executors/build/schema.json +0 -82
  61. package/dist/src/executors/dev-server/compat.d.ts +0 -2
  62. package/dist/src/executors/dev-server/compat.js +0 -6
  63. package/dist/src/executors/dev-server/dev-server.impl.d.ts +0 -7
  64. package/dist/src/executors/dev-server/dev-server.impl.js +0 -137
  65. package/dist/src/executors/dev-server/schema.json +0 -40
  66. package/dist/src/executors/preview-server/compat.d.ts +0 -2
  67. package/dist/src/executors/preview-server/compat.js +0 -6
  68. package/dist/src/executors/preview-server/preview-server.impl.d.ts +0 -7
  69. package/dist/src/executors/preview-server/preview-server.impl.js +0 -184
  70. package/dist/src/executors/preview-server/schema.json +0 -44
  71. package/dist/src/utils/nx-tsconfig-paths-find-file.d.ts +0 -2
  72. package/dist/src/utils/nx-tsconfig-paths-find-file.js +0 -22
  73. package/dist/src/utils/nx-tsconfig-paths-load-file.d.ts +0 -12
  74. package/dist/src/utils/nx-tsconfig-paths-load-file.js +0 -71
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseViteFlags = parseViteFlags;
4
+ exports.getViteServerAddress = getViteServerAddress;
5
+ exports.waitForViteServer = waitForViteServer;
6
+ const internal_1 = require("@nx/devkit/internal");
7
+ const net_1 = require("net");
8
+ const path_1 = require("path");
9
+ const executor_utils_1 = require("./executor-utils");
10
+ // Vite's boolean options: the arg after one is positional, not its value
11
+ const GLOBAL_BOOLEAN_OPTIONS = ['clearScreen', 'h', 'help', 'v', 'version'];
12
+ const BOOLEAN_OPTIONS = {
13
+ serve: [
14
+ ...GLOBAL_BOOLEAN_OPTIONS,
15
+ 'cors',
16
+ 'strictPort',
17
+ 'force',
18
+ 'experimentalBundle',
19
+ ],
20
+ preview: [...GLOBAL_BOOLEAN_OPTIONS, 'strictPort'],
21
+ };
22
+ /**
23
+ * The flags `vite` and `vite preview` get from the target's options, in the
24
+ * order run-commands passes them: named options, `args`, then overrides.
25
+ */
26
+ function parseViteFlags(options, command) {
27
+ const args = Array.isArray(options.args)
28
+ ? options.args.join(' ')
29
+ : typeof options.args === 'string'
30
+ ? options.args
31
+ : '';
32
+ const unparsed = Array.isArray(options.__unparsed__)
33
+ ? options.__unparsed__.map(String)
34
+ : [];
35
+ // run-commands skips a named option the overrides set, or that args set to
36
+ // another value, parsing both with nx's yargs-parser
37
+ const yargsParser = require(require.resolve('yargs-parser', {
38
+ paths: [(0, path_1.dirname)(require.resolve('nx/package.json'))],
39
+ }));
40
+ const overrides = yargsParser(unparsed, {
41
+ configuration: {
42
+ 'parse-numbers': false,
43
+ 'parse-positional-numbers': false,
44
+ 'dot-notation': false,
45
+ 'camel-case-expansion': false,
46
+ },
47
+ });
48
+ const fromArgs = args
49
+ ? yargsParser(args.replace(/(^"|"$)/g, ''), {
50
+ configuration: { 'camel-case-expansion': true },
51
+ })
52
+ : {};
53
+ const named = Object.keys(options)
54
+ .filter((k) => ['port', 'host', 'mode', 'm', 'config', 'c'].includes(k) &&
55
+ typeof options[k] !== 'object' &&
56
+ overrides[k] === undefined &&
57
+ (!Object.hasOwn(fromArgs, k) || fromArgs[k] === options[k]))
58
+ .map((k) => `--${k}=${options[k]}`);
59
+ const { values, positionals } = parseArgv([...named, ...(0, internal_1.splitShellArgs)(args), ...unparsed], BOOLEAN_OPTIONS[command]);
60
+ // Vite keeps the values of whichever spelling of an option comes first
61
+ const last = (...names) => values.get([...values.keys()].find((k) => names.includes(k)))?.at(-1);
62
+ const asString = (value) => typeof value === 'string' ? value : undefined;
63
+ return {
64
+ port: asString(last('port')),
65
+ host: last('host'),
66
+ mode: asString(last('m', 'mode')),
67
+ config: asString(last('c', 'config')),
68
+ root: positionals[0],
69
+ };
70
+ }
71
+ // A port of the mri parser Vite's CLI uses, keeping each option's values
72
+ function parseArgv(argv, booleans) {
73
+ const values = new Map();
74
+ const positionals = [];
75
+ const add = (name, value) => values.set(name, [...(values.get(name) ?? []), value]);
76
+ for (let i = 0; i < argv.length; i++) {
77
+ const arg = argv[i];
78
+ if (arg === '--')
79
+ break;
80
+ const dashes = arg.match(/^-*/)[0].length;
81
+ if (dashes === 0) {
82
+ positionals.push(arg);
83
+ continue;
84
+ }
85
+ if (arg.startsWith('no-', dashes)) {
86
+ add(arg.slice(dashes + 3), false);
87
+ continue;
88
+ }
89
+ const eq = arg.indexOf('=', dashes + 1);
90
+ const name = arg.slice(dashes, eq === -1 ? undefined : eq);
91
+ const value = (eq === -1 ? '' : arg.slice(eq + 1)) ||
92
+ i + 1 === argv.length ||
93
+ argv[i + 1].startsWith('-') ||
94
+ argv[++i];
95
+ // `-abc` sets a, b and c, and the value goes to c
96
+ const names = dashes === 2 ? [name] : [...name];
97
+ names.forEach((n, j) => {
98
+ const v = j === names.length - 1 ? value : true;
99
+ if (typeof v === 'string' && booleans.includes(n)) {
100
+ if (v !== 'true' && v !== 'false')
101
+ positionals.push(v);
102
+ add(n, v !== 'false');
103
+ }
104
+ else {
105
+ add(n, v);
106
+ }
107
+ });
108
+ }
109
+ return { values, positionals };
110
+ }
111
+ // Vite's default ports: https://vite.dev/config/server-options#server-port
112
+ const DEFAULT_PORT = { serve: 5173, preview: 4173 };
113
+ function getViteServerAddress(server, flags, command) {
114
+ const port = Number(flags.port ?? server?.port ?? DEFAULT_PORT[command]);
115
+ if (!Number.isInteger(port) || port <= 0)
116
+ return null;
117
+ const host = flags.host ?? server?.host;
118
+ // `true` and the wildcards listen on every address, loopback included
119
+ return typeof host === 'string' &&
120
+ !['localhost', '0.0.0.0', '::'].includes(host)
121
+ ? { port, host }
122
+ : { port };
123
+ }
124
+ /**
125
+ * The readyWhen of the inferred serve and preview targets when the config
126
+ * doesn't load the signal plugin. Runs in the env and with the options of the
127
+ * task, resolves the config the way `vite` does, and waits for the server's
128
+ * port.
129
+ */
130
+ async function waitForViteServer(configPath, command) {
131
+ let options = {};
132
+ try {
133
+ options = JSON.parse(process.env.NX_TASK_OPTIONS ?? '{}');
134
+ }
135
+ catch { }
136
+ const flags = parseViteFlags(options, command);
137
+ process.chdir((0, path_1.resolve)(options.cwd ?? '.'));
138
+ const { resolveConfig } = await (0, executor_utils_1.loadViteDynamicImport)();
139
+ const inlineConfig = {
140
+ root: flags.root,
141
+ // With --root and no --config, Vite finds the config in the root, not in
142
+ // the task's cwd
143
+ configFile: flags.config ?? (flags.root ? undefined : configPath),
144
+ mode: flags.mode,
145
+ };
146
+ // The mode and NODE_ENV defaults of `vite` and `vite preview`
147
+ const config = command === 'preview'
148
+ ? await resolveConfig(inlineConfig, 'serve', 'production', 'production', true)
149
+ : await resolveConfig(inlineConfig, 'serve');
150
+ const address = getViteServerAddress(command === 'preview'
151
+ ? { ...config.preview, host: config.preview.host ?? config.server.host }
152
+ : config.server, flags, command);
153
+ if (address)
154
+ await waitForAddress(address);
155
+ }
156
+ async function waitForAddress({ port, host }) {
157
+ const hosts = host ? [host] : ['127.0.0.1', '::1'];
158
+ while (!(await Promise.any(hosts.map((h) => connects(port, h))).catch(() => false))) {
159
+ await new Promise((r) => setTimeout(r, 250));
160
+ }
161
+ }
162
+ function connects(port, host) {
163
+ return new Promise((resolve, reject) => {
164
+ const socket = (0, net_1.createConnection)({ port, host });
165
+ socket.once('connect', () => {
166
+ socket.destroy();
167
+ resolve(true);
168
+ });
169
+ socket.once('error', (e) => {
170
+ socket.destroy();
171
+ reject(e);
172
+ });
173
+ });
174
+ }
@@ -1,3 +1,3 @@
1
1
  import { type Tree } from '@nx/devkit';
2
- export declare function getViteE2EWebServerInfo(tree: Tree, projectName: string, configFilePath: string, isPluginBeingAdded: boolean, e2ePortOverride?: number, e2eCIPortOverride?: number): Promise<import("@nx/devkit/internal").E2EWebServerDetails>;
3
- export declare function getReactRouterE2EWebServerInfo(tree: Tree, projectName: string, configFilePath: string, isPluginBeingAdded: boolean, e2ePortOverride?: number, e2eCIPortOverride?: number): Promise<import("@nx/devkit/internal").E2EWebServerDetails>;
2
+ export declare function getViteE2EWebServerInfo(tree: Tree, projectName: string, configFilePath: string, e2ePortOverride?: number, e2eCIPortOverride?: number): Promise<import("@nx/devkit/internal").E2EWebServerDetails>;
3
+ export declare function getReactRouterE2EWebServerInfo(tree: Tree, projectName: string, configFilePath: string, e2ePortOverride?: number, e2eCIPortOverride?: number): Promise<import("@nx/devkit/internal").E2EWebServerDetails>;
@@ -4,7 +4,7 @@ exports.getViteE2EWebServerInfo = getViteE2EWebServerInfo;
4
4
  exports.getReactRouterE2EWebServerInfo = getReactRouterE2EWebServerInfo;
5
5
  const devkit_1 = require("@nx/devkit");
6
6
  const internal_1 = require("@nx/devkit/internal");
7
- async function getViteE2EWebServerInfo(tree, projectName, configFilePath, isPluginBeingAdded, e2ePortOverride, e2eCIPortOverride) {
7
+ async function getViteE2EWebServerInfo(tree, projectName, configFilePath, e2ePortOverride, e2eCIPortOverride) {
8
8
  const nxJson = (0, devkit_1.readNxJson)(tree);
9
9
  let e2ePort = e2ePortOverride ?? 4200;
10
10
  const devPort = (0, internal_1.readTargetDefaultsForTarget)('dev', nxJson.targetDefaults)
@@ -25,9 +25,9 @@ async function getViteE2EWebServerInfo(tree, projectName, configFilePath, isPlug
25
25
  defaultE2EWebServerAddress: `http://localhost:${e2ePort}`,
26
26
  defaultE2ECiBaseUrl: `http://localhost:${e2eCIPortOverride ?? 4300}`,
27
27
  defaultE2EPort: e2ePort,
28
- }, isPluginBeingAdded);
28
+ });
29
29
  }
30
- async function getReactRouterE2EWebServerInfo(tree, projectName, configFilePath, isPluginBeingAdded, e2ePortOverride, e2eCIPortOverride) {
30
+ async function getReactRouterE2EWebServerInfo(tree, projectName, configFilePath, e2ePortOverride, e2eCIPortOverride) {
31
31
  const e2ePort = e2ePortOverride ?? parseInt(process.env.PORT) ?? 4200;
32
32
  return await (0, internal_1.getE2EWebServerInfo)(tree, projectName, {
33
33
  plugin: '@nx/react/router-plugin',
@@ -40,5 +40,5 @@ async function getReactRouterE2EWebServerInfo(tree, projectName, configFilePath,
40
40
  defaultE2EWebServerAddress: `http://localhost:${e2ePort}`,
41
41
  defaultE2ECiBaseUrl: `http://localhost:${e2eCIPortOverride ?? 4200}`,
42
42
  defaultE2EPort: e2ePort,
43
- }, isPluginBeingAdded);
43
+ });
44
44
  }
@@ -1,11 +1 @@
1
- import { ExecutorContext } from '@nx/devkit';
2
- export declare function validateTypes(opts: {
3
- workspaceRoot: string;
4
- tsconfig: string;
5
- isVueProject?: boolean;
6
- }): Promise<void>;
7
- export declare function createBuildableTsConfig(projectRoot: string, options: {
8
- tsConfig?: string;
9
- buildLibsFromSource?: boolean;
10
- }, context: ExecutorContext): string;
11
1
  export declare function loadViteDynamicImport(): Promise<typeof import('vite')>;
@@ -1,57 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateTypes = validateTypes;
4
- exports.createBuildableTsConfig = createBuildableTsConfig;
5
3
  exports.loadViteDynamicImport = loadViteDynamicImport;
6
- const devkit_1 = require("@nx/devkit");
7
- const internal_1 = require("@nx/js/internal");
8
- const options_utils_1 = require("./options-utils");
9
- const node_child_process_1 = require("node:child_process");
10
- const js_1 = require("@nx/js");
11
- const path_1 = require("path");
12
- async function validateTypes(opts) {
13
- if (!opts.isVueProject) {
14
- const result = await (0, js_1.runTypeCheck)({
15
- workspaceRoot: opts.workspaceRoot,
16
- tsConfigPath: opts.tsconfig.startsWith(opts.workspaceRoot)
17
- ? opts.tsconfig
18
- : (0, path_1.join)(opts.workspaceRoot, opts.tsconfig),
19
- mode: 'noEmit',
20
- // TS 6 defaults rootDir to the tsconfig dir, so from-source workspace
21
- // libs (outside the project) trip TS6059. rootDir is emit-only and this
22
- // is noEmit, so widen it to the workspace root to clear the false error.
23
- rootDir: opts.workspaceRoot,
24
- });
25
- await (0, js_1.printDiagnostics)(result.errors, result.warnings);
26
- if (result.errors.length > 0) {
27
- throw new Error('Found type errors. See above.');
28
- }
29
- }
30
- else {
31
- const pm = (0, devkit_1.getPackageManagerCommand)();
32
- const cp = (0, node_child_process_1.execSync)(`${pm.exec} vue-tsc --noEmit -p ${opts.tsconfig} --composite false`, {
33
- cwd: opts.workspaceRoot,
34
- stdio: 'inherit',
35
- windowsHide: true,
36
- });
37
- }
38
- }
39
- function createBuildableTsConfig(projectRoot, options, context) {
40
- const tsConfig = options.tsConfig ?? (0, options_utils_1.getProjectTsConfigPath)(projectRoot);
41
- options['buildLibsFromSource'] ??= true;
42
- if (!options['buildLibsFromSource']) {
43
- const { dependencies } = (0, internal_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName,
44
- // When using incremental building and the serve target is called
45
- // we need to get the deps for the 'build' target instead.
46
- context.targetName === 'serve' ? 'build' : context.targetName, context.configurationName);
47
- // This tsconfig is used via the Vite ts paths plugin.
48
- // It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).
49
- const tmpTsConfigPath = (0, internal_1.createTmpTsConfig)(tsConfig, context.root, projectRoot, dependencies);
50
- process.env.NX_TSCONFIG_PATH = tmpTsConfigPath;
51
- return tmpTsConfigPath;
52
- }
53
- return tsConfig;
54
- }
55
4
  function loadViteDynamicImport() {
56
5
  return Function('return import("vite")')();
57
6
  }
@@ -10,16 +10,7 @@ export declare function findExistingJsBuildTargetInProject(targets: {
10
10
  supported?: string;
11
11
  unsupported?: string;
12
12
  };
13
- export declare function addBuildTarget(tree: Tree, options: ViteConfigurationGeneratorSchema, target: string): void;
14
- export declare function addServeTarget(tree: Tree, options: ViteConfigurationGeneratorSchema, target: string): void;
15
- /**
16
- * Adds a target for the preview server.
17
- *
18
- * @param tree
19
- * @param options
20
- * @param serveTarget An existing serve target.
21
- */
22
- export declare function addPreviewTarget(tree: Tree, options: ViteConfigurationGeneratorSchema, serveTarget: string): void;
13
+ export declare function assertNoRemovedExecutorTargets(projectName: string, targets: Record<string, TargetConfiguration> | undefined): void;
23
14
  export declare function editTsConfig(tree: Tree, options: ViteConfigurationGeneratorSchema): void;
24
15
  export declare function deleteWebpackConfig(tree: Tree, projectRoot: string, webpackConfigFilePath?: string): void;
25
16
  export declare function moveAndEditIndexHtml(tree: Tree, options: ViteConfigurationGeneratorSchema): void;
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.findExistingJsBuildTargetInProject = findExistingJsBuildTargetInProject;
4
- exports.addBuildTarget = addBuildTarget;
5
- exports.addServeTarget = addServeTarget;
6
- exports.addPreviewTarget = addPreviewTarget;
4
+ exports.assertNoRemovedExecutorTargets = assertNoRemovedExecutorTargets;
7
5
  exports.editTsConfig = editTsConfig;
8
6
  exports.deleteWebpackConfig = deleteWebpackConfig;
9
7
  exports.moveAndEditIndexHtml = moveAndEditIndexHtml;
@@ -16,10 +14,12 @@ const internal_1 = require("@nx/devkit/internal");
16
14
  const devkit_1 = require("@nx/devkit");
17
15
  const internal_2 = require("@nx/js/internal");
18
16
  const vite_config_edit_utils_1 = require("./vite-config-edit-utils");
17
+ const version_utils_1 = require("./version-utils");
18
+ const versions_1 = require("./versions");
19
19
  function findExistingJsBuildTargetInProject(targets) {
20
20
  const output = {};
21
21
  const supportedExecutors = {
22
- build: ['@nx/js:babel', '@nx/js:swc', '@nx/rollup:rollup'],
22
+ build: ['@nx/js:swc'],
23
23
  };
24
24
  const unsupportedExecutors = [
25
25
  '@nx/angular:ng-packagr-lite',
@@ -63,92 +63,23 @@ function findExistingJsBuildTargetInProject(targets) {
63
63
  }
64
64
  return output;
65
65
  }
66
- function addBuildTarget(tree, options, target) {
67
- (0, internal_1.addBuildTargetDefaults)(tree, '@nx/vite:build');
68
- const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
69
- const isTsSolutionSetup = (0, internal_2.isUsingTsSolutionSetup)(tree);
70
- const buildOptions = {
71
- outputPath: isTsSolutionSetup
72
- ? (0, devkit_1.joinPathFragments)(project.root, 'dist')
73
- : (0, devkit_1.joinPathFragments)('dist', project.root != '.' ? project.root : options.project),
74
- };
75
- project.targets ??= {};
76
- project.targets[target] = {
77
- executor: '@nx/vite:build',
78
- outputs: ['{options.outputPath}'],
79
- defaultConfiguration: 'production',
80
- options: buildOptions,
81
- configurations: {
82
- development: {
83
- mode: 'development',
84
- },
85
- production: {
86
- mode: 'production',
87
- },
88
- },
89
- };
90
- (0, devkit_1.updateProjectConfiguration)(tree, options.project, project);
91
- }
92
- function addServeTarget(tree, options, target) {
93
- const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
94
- project.targets ??= {};
95
- project.targets[target] = {
96
- executor: '@nx/vite:dev-server',
97
- defaultConfiguration: 'development',
98
- options: {
99
- buildTarget: `${options.project}:build`,
100
- },
101
- configurations: {
102
- development: {
103
- buildTarget: `${options.project}:build:development`,
104
- hmr: true,
105
- },
106
- production: {
107
- buildTarget: `${options.project}:build:production`,
108
- hmr: false,
109
- },
110
- },
111
- };
112
- (0, devkit_1.updateProjectConfiguration)(tree, options.project, project);
113
- }
114
- /**
115
- * Adds a target for the preview server.
116
- *
117
- * @param tree
118
- * @param options
119
- * @param serveTarget An existing serve target.
120
- */
121
- function addPreviewTarget(tree, options, serveTarget) {
122
- const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
123
- const previewOptions = {
124
- buildTarget: `${options.project}:build`,
125
- };
126
- project.targets ??= {};
127
- // Update the options from the passed serve target.
128
- if (project.targets[serveTarget]) {
129
- const target = project.targets[serveTarget];
130
- if (target.executor === '@nxext/vite:dev') {
131
- previewOptions.proxyConfig = target.options.proxyConfig;
132
- }
133
- previewOptions['https'] = target.options?.https;
134
- previewOptions['open'] = target.options?.open;
66
+ // A leftover target on one of these can't run, and it shadows the inferred
67
+ // target with the same name, so converting around it leaves a broken project.
68
+ const removedConvertibleExecutors = [
69
+ '@nx/rollup:rollup',
70
+ '@nx/vite:build',
71
+ '@nx/vite:dev-server',
72
+ '@nx/vite:preview-server',
73
+ '@nx/webpack:dev-server',
74
+ '@nx/webpack:webpack',
75
+ ];
76
+ function assertNoRemovedExecutorTargets(projectName, targets) {
77
+ const removedTargets = Object.entries(targets ?? {})
78
+ .filter(([, target]) => removedConvertibleExecutors.includes(target.executor))
79
+ .map(([targetName, target]) => `${targetName} (${target.executor})`);
80
+ if (removedTargets.length) {
81
+ throw new Error(`The project ${projectName} has targets using removed executors: ${removedTargets.join(', ')}. Convert them to inferred targets first, for example with "nx g @nx/workspace:infer-targets --project=${projectName}".`);
135
82
  }
136
- // Adds a preview target.
137
- project.targets.preview = {
138
- dependsOn: ['build'],
139
- executor: '@nx/vite:preview-server',
140
- defaultConfiguration: 'development',
141
- options: previewOptions,
142
- configurations: {
143
- development: {
144
- buildTarget: `${options.project}:build:development`,
145
- },
146
- production: {
147
- buildTarget: `${options.project}:build:production`,
148
- },
149
- },
150
- };
151
- (0, devkit_1.updateProjectConfiguration)(tree, options.project, project);
152
83
  }
153
84
  function editTsConfig(tree, options) {
154
85
  const projectConfig = (0, devkit_1.readProjectConfiguration)(tree, options.project);
@@ -285,18 +216,38 @@ function createOrEditViteConfig(tree, options, onlyVitest, projectAlreadyHasVite
285
216
  },`;
286
217
  const imports = options.imports ? [...options.imports] : [];
287
218
  const plugins = options.plugins ? [...options.plugins] : [];
219
+ const needsPaths = !isTsSolutionSetup;
220
+ const useNativePaths = needsPaths && ((0, version_utils_1.getInstalledViteMajorVersion)(tree) ?? 8) >= 8;
221
+ const dependencies = {};
222
+ if (needsPaths && !useNativePaths) {
223
+ imports.push(`import tsconfigPaths from 'vite-tsconfig-paths'`);
224
+ plugins.push('tsconfigPaths({ loose: true })');
225
+ dependencies['vite-tsconfig-paths'] = versions_1.viteTsconfigPathsVersion;
226
+ }
227
+ if (!onlyVitest && options.includeLib && !isTsSolutionSetup) {
228
+ plugins.push(`import('vite-plugin-static-copy').then(({ viteStaticCopy }) => viteStaticCopy({
229
+ targets: [
230
+ { src: '*.md', dest: '.' },
231
+ { src: 'package.json', dest: '.', overwrite: false },
232
+ ],
233
+ silent: true,
234
+ }))`);
235
+ dependencies['vite-plugin-static-copy'] = versions_1.viteStaticCopyVersion;
236
+ }
237
+ if (Object.keys(dependencies).length) {
238
+ (0, devkit_1.addDependenciesToPackageJson)(tree, {}, dependencies, undefined, true);
239
+ }
288
240
  if (!onlyVitest && options.includeLib) {
289
241
  imports.push(`import dts from 'vite-plugin-dts'`, `import * as path from 'path'`);
290
242
  }
291
- if (!isTsSolutionSetup) {
292
- // TODO(v24): drop this branch; emit `tsconfigPaths()` from
293
- // `vite-tsconfig-paths` instead of the deprecated nx helpers.
294
- imports.push(`import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'`, `import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin'`);
295
- plugins.push(`nxViteTsPaths()`, `nxCopyAssetsPlugin(['*.md'])`);
296
- }
297
243
  if (!onlyVitest && options.includeLib) {
298
244
  plugins.push(`dts({ entryRoot: 'src', tsconfigPath: path.join(import.meta.dirname, 'tsconfig.lib.json')${!isTsSolutionSetup ? ', pathsToAliases: false' : ''} })`);
299
245
  }
246
+ // Lets the inferred serve and preview targets know when the server is up
247
+ if (!onlyVitest && !options.includeLib) {
248
+ imports.push(`import { nxReadySignal } from '@nx/vite/plugins/nx-ready-signal.plugin'`);
249
+ plugins.push('nxReadySignal()');
250
+ }
300
251
  const reportsDirectory = isTsSolutionSetup
301
252
  ? './test-output/vitest/coverage'
302
253
  : projectRoot === '.'
@@ -343,18 +294,21 @@ ${options.inSourceTests
343
294
  port: ${options.previewPort ?? 4300},
344
295
  host: 'localhost',
345
296
  },`;
346
- const workerOption = isTsSolutionSetup
347
- ? ` // Uncomment this if you are using workers.
297
+ const workerOption = ` // Uncomment this if you are using workers.
348
298
  // worker: {
349
299
  // plugins: [],
350
- // },`
351
- : ` // Uncomment this if you are using workers.
352
- // worker: {
353
- // plugins: () => [ nxViteTsPaths() ],
354
300
  // },`;
301
+ // Path-based workspace libraries need Vite's native tsconfig paths
302
+ // resolution, which is off by default. Workspaces on project references
303
+ // resolve through package.json instead.
304
+ const resolveOption = !useNativePaths
305
+ ? ''
306
+ : ` resolve: {
307
+ tsconfigPaths: true,
308
+ },`;
355
309
  const cacheDir = `cacheDir: '${normalizedJoinPaths((0, devkit_1.offsetFromRoot)(projectRoot), 'node_modules', '.vite', projectRoot === '.' ? options.project : projectRoot)}',`;
356
310
  if (tree.exists(viteConfigPath)) {
357
- handleViteConfigFileExists(tree, viteConfigPath, options, buildOption, buildOutDir, imports, plugins, testOption, reportsDirectory, cacheDir, projectRoot, (0, devkit_1.offsetFromRoot)(projectRoot), projectAlreadyHasViteTargets);
311
+ handleViteConfigFileExists(tree, viteConfigPath, options, buildOption, buildOutDir, imports, plugins, testOption, reportsDirectory, cacheDir, projectRoot, (0, devkit_1.offsetFromRoot)(projectRoot), projectAlreadyHasViteTargets, useNativePaths);
358
312
  return;
359
313
  }
360
314
  const viteConfigContent = `/// <reference types='vitest' />
@@ -363,7 +317,7 @@ ${imports.join(';\n')}${imports.length ? ';' : ''}
363
317
 
364
318
  export default defineConfig(() => ({
365
319
  root: import.meta.dirname,
366
- ${printOptions(cacheDir, devServerOption, previewServerOption, ` plugins: [${plugins.join(', ')}],`, workerOption, buildOption, defineOption, testOption)}
320
+ ${printOptions(cacheDir, devServerOption, previewServerOption, resolveOption, plugins.length ? ` plugins: [${plugins.join(', ')}],` : '', workerOption, buildOption, defineOption, testOption)}
367
321
  }));
368
322
  `.replace(/\s+(?=(\n|$))/gm, '\n');
369
323
  tree.write(viteConfigPath, viteConfigContent);
@@ -383,16 +337,10 @@ function normalizeViteConfigFilePathWithTree(tree, projectRoot, configFile) {
383
337
  : undefined;
384
338
  }
385
339
  function getViteConfigPathForProject(tree, projectName, target) {
386
- let viteConfigPath;
387
340
  const { targets, root } = (0, devkit_1.readProjectConfiguration)(tree, projectName);
388
- if (target) {
389
- viteConfigPath = targets?.[target]?.options?.configFile;
390
- }
391
- else {
392
- const config = Object.values(targets).find((config) => config.executor === '@nrwl/nx:build' ||
393
- config.executor === '@nrwl/vite:build');
394
- viteConfigPath = config?.options?.configFile;
395
- }
341
+ const viteConfigPath = target
342
+ ? targets?.[target]?.options?.configFile
343
+ : undefined;
396
344
  return normalizeViteConfigFilePathWithTree(tree, root, viteConfigPath);
397
345
  }
398
346
  async function handleUnsupportedUserProvidedTargets(userProvidedTargetIsUnsupported, userProvidedTargetName, validFoundTargetName) {
@@ -447,7 +395,7 @@ async function handleUnknownConfiguration(projectName) {
447
395
  `);
448
396
  }
449
397
  }
450
- function handleViteConfigFileExists(tree, viteConfigPath, options, buildOption, buildOutDir, imports, plugins, testOption, reportsDirectory, cacheDir, projectRoot, offsetFromRoot, projectAlreadyHasViteTargets) {
398
+ function handleViteConfigFileExists(tree, viteConfigPath, options, buildOption, buildOutDir, imports, plugins, testOption, reportsDirectory, cacheDir, projectRoot, offsetFromRoot, projectAlreadyHasViteTargets, resolveTsconfigPaths) {
451
399
  if (projectAlreadyHasViteTargets?.build &&
452
400
  projectAlreadyHasViteTargets?.test) {
453
401
  return;
@@ -489,7 +437,7 @@ function handleViteConfigFileExists(tree, viteConfigPath, options, buildOption,
489
437
  provider: `'${options.coverageProvider ?? 'v8'}'`,
490
438
  },
491
439
  };
492
- const changed = (0, vite_config_edit_utils_1.ensureViteConfigIsCorrect)(tree, viteConfigPath, buildOption, buildOptionObject, imports, plugins, testOption, testOptionObject, cacheDir, projectAlreadyHasViteTargets ?? {});
440
+ const changed = (0, vite_config_edit_utils_1.ensureViteConfigIsCorrect)(tree, viteConfigPath, buildOption, buildOptionObject, imports, plugins, testOption, testOptionObject, cacheDir, projectAlreadyHasViteTargets ?? {}, resolveTsconfigPaths);
493
441
  if (!changed) {
494
442
  devkit_1.logger.warn(`Make sure the following setting exists in your Vite configuration file (${viteConfigPath}):
495
443
 
@@ -1,17 +1 @@
1
- import { ExecutorContext } from '@nx/devkit';
2
- import { ViteDevServerExecutorOptions } from '../executors/dev-server/schema';
3
- /**
4
- * Returns the path to the vite config file or undefined when not found.
5
- */
6
- export declare function normalizeViteConfigFilePath(contextRoot: string, projectRoot: string, configFile?: string): string | undefined;
7
1
  export declare function getProjectTsConfigPath(projectRoot: string): string | undefined;
8
- /**
9
- * Returns the path to the proxy configuration file or undefined when not found.
10
- */
11
- export declare function getViteServerProxyConfigPath(nxProxyConfig: string | undefined, context: ExecutorContext): string | undefined;
12
- /**
13
- * Builds the options for the vite dev server.
14
- */
15
- export declare function getViteServerOptions(options: ViteDevServerExecutorOptions, context: ExecutorContext): Promise<Record<string, unknown>>;
16
- export declare function getProxyConfig(context: ExecutorContext, proxyConfig?: string): Record<string, string | unknown> | undefined;
17
- export declare function getNxTargetOptions(target: string, context: ExecutorContext): any;
@@ -1,32 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalizeViteConfigFilePath = normalizeViteConfigFilePath;
4
3
  exports.getProjectTsConfigPath = getProjectTsConfigPath;
5
- exports.getViteServerProxyConfigPath = getViteServerProxyConfigPath;
6
- exports.getViteServerOptions = getViteServerOptions;
7
- exports.getProxyConfig = getProxyConfig;
8
- exports.getNxTargetOptions = getNxTargetOptions;
9
4
  const devkit_1 = require("@nx/devkit");
10
5
  const fs_1 = require("fs");
11
- const executor_utils_1 = require("./executor-utils");
12
- /**
13
- * Returns the path to the vite config file or undefined when not found.
14
- */
15
- function normalizeViteConfigFilePath(contextRoot, projectRoot, configFile) {
16
- if (configFile) {
17
- const normalized = (0, devkit_1.joinPathFragments)(contextRoot, configFile);
18
- if (!(0, fs_1.existsSync)(normalized)) {
19
- throw new Error(`Could not find vite config at provided path "${normalized}".`);
20
- }
21
- return normalized;
22
- }
23
- const allowsExt = ['js', 'mjs', 'ts', 'cjs', 'mts', 'cts'];
24
- for (const ext of allowsExt) {
25
- if ((0, fs_1.existsSync)((0, devkit_1.joinPathFragments)(contextRoot, projectRoot, `vite.config.${ext}`))) {
26
- return (0, devkit_1.joinPathFragments)(contextRoot, projectRoot, `vite.config.${ext}`);
27
- }
28
- }
29
- }
30
6
  function getProjectTsConfigPath(projectRoot) {
31
7
  return (0, fs_1.existsSync)((0, devkit_1.joinPathFragments)(devkit_1.workspaceRoot, projectRoot, 'tsconfig.app.json'))
32
8
  ? (0, devkit_1.joinPathFragments)(projectRoot, 'tsconfig.app.json')
@@ -36,52 +12,3 @@ function getProjectTsConfigPath(projectRoot) {
36
12
  ? (0, devkit_1.joinPathFragments)(projectRoot, 'tsconfig.json')
37
13
  : undefined;
38
14
  }
39
- /**
40
- * Returns the path to the proxy configuration file or undefined when not found.
41
- */
42
- function getViteServerProxyConfigPath(nxProxyConfig, context) {
43
- if (nxProxyConfig) {
44
- const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
45
- const proxyConfigPath = nxProxyConfig
46
- ? (0, devkit_1.joinPathFragments)(context.root, nxProxyConfig)
47
- : (0, devkit_1.joinPathFragments)(projectRoot, 'proxy.conf.json');
48
- if ((0, fs_1.existsSync)(proxyConfigPath)) {
49
- return proxyConfigPath;
50
- }
51
- }
52
- }
53
- /**
54
- * Builds the options for the vite dev server.
55
- */
56
- async function getViteServerOptions(options, context) {
57
- // returns vite ServerOptions
58
- // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future.
59
- const { searchForWorkspaceRoot } = await (0, executor_utils_1.loadViteDynamicImport)();
60
- const projectRoot = context.projectsConfigurations.projects[context.projectName].root;
61
- const serverOptions = {
62
- fs: {
63
- allow: [
64
- searchForWorkspaceRoot((0, devkit_1.joinPathFragments)(projectRoot)),
65
- (0, devkit_1.joinPathFragments)(context.root, 'node_modules/vite'),
66
- ],
67
- },
68
- };
69
- const proxyConfigPath = getViteServerProxyConfigPath(options.proxyConfig, context);
70
- if (proxyConfigPath) {
71
- devkit_1.logger.info(`Loading proxy configuration from: ${proxyConfigPath}`);
72
- serverOptions.proxy = require(proxyConfigPath);
73
- }
74
- return serverOptions;
75
- }
76
- function getProxyConfig(context, proxyConfig) {
77
- const proxyConfigPath = getViteServerProxyConfigPath(proxyConfig, context);
78
- if (proxyConfigPath) {
79
- devkit_1.logger.info(`Loading proxy configuration from: ${proxyConfigPath}`);
80
- return require(proxyConfigPath);
81
- }
82
- return;
83
- }
84
- function getNxTargetOptions(target, context) {
85
- const targetObj = (0, devkit_1.parseTargetString)(target, context);
86
- return (0, devkit_1.readTargetOptions)(targetObj, context);
87
- }
@@ -10,3 +10,5 @@ export declare const vitePluginReactSwcVersion = "^4.3.0";
10
10
  export declare const vitePluginDtsVersion = "~4.5.0";
11
11
  export declare const ajvVersion = "^8.0.0";
12
12
  export declare const jitiVersion = "2.4.2";
13
+ export declare const viteTsconfigPathsVersion = "~4.3.2";
14
+ export declare const viteStaticCopyVersion = "^3.3.0";