@nx/vitest 23.2.0-beta.5 → 23.2.0-beta.6

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.
@@ -17,6 +17,17 @@ const versions_1 = require("../../utils/versions");
17
17
  const assert_supported_vitest_version_1 = require("../../utils/assert-supported-vitest-version");
18
18
  const semver_1 = require("semver");
19
19
  let ts;
20
+ // Must match `vitestWorkspaceFiles` in ../../plugins/plugin.ts, or the guards
21
+ // here and inference disagree about what counts as an existing workspace file.
22
+ const WORKSPACE_FILE_EXTENSIONS = [
23
+ 'ts',
24
+ 'mts',
25
+ 'cts',
26
+ 'js',
27
+ 'mjs',
28
+ 'cjs',
29
+ 'json',
30
+ ];
20
31
  /**
21
32
  * Determines whether to use vitest.config.mts instead of vite.config.mts.
22
33
  * Returns true for new non-framework projects that don't already have a vite.config.
@@ -188,7 +199,7 @@ getTestBed().initTestEnvironment(
188
199
  const projectGlobs = `'**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'`;
189
200
  const vitestMajorVersion = (0, versions_1.getInstalledVitestMajorVersion)(tree);
190
201
  if (vitestMajorVersion === null || vitestMajorVersion >= 4) {
191
- const hasWorkspaceFile = ['ts', 'js', 'json'].some((ext) => tree.exists(`vitest.workspace.${ext}`) ||
202
+ const hasWorkspaceFile = WORKSPACE_FILE_EXTENSIONS.some((ext) => tree.exists(`vitest.workspace.${ext}`) ||
192
203
  tree.exists(`vitest.projects.${ext}`));
193
204
  const rootVitestConfig = findRootConfig(tree, 'vitest.config');
194
205
  const rootViteConfig = findRootConfig(tree, 'vite.config');
@@ -241,7 +252,9 @@ getTestBed().initTestEnvironment(
241
252
  // root vite.config added later; exclude both so neither is resolved as
242
253
  // an extra project that, carrying no `include`, re-runs every spec via
243
254
  // the default glob.
244
- tree.write('vitest.config.ts', `import { defineConfig } from 'vitest/config';
255
+ // `.mts` keeps it ESM whatever the root package.json `type` is; a
256
+ // CommonJS-loaded config trips Vite's `configLoader: 'native'` warning.
257
+ tree.write('vitest.config.mts', `import { defineConfig } from 'vitest/config';
245
258
 
246
259
  export default defineConfig({
247
260
  test: {
@@ -251,13 +264,9 @@ export default defineConfig({
251
264
  `);
252
265
  }
253
266
  }
254
- else if (!tree.exists(`vitest.workspace.ts`) &&
255
- !tree.exists(`vitest.workspace.js`) &&
256
- !tree.exists(`vitest.workspace.json`) &&
257
- !tree.exists(`vitest.projects.ts`) &&
258
- !tree.exists(`vitest.projects.js`) &&
259
- !tree.exists(`vitest.projects.json`)) {
260
- tree.write('vitest.workspace.ts', `export default [${projectGlobs}];`);
267
+ else if (!WORKSPACE_FILE_EXTENSIONS.some((ext) => tree.exists(`vitest.workspace.${ext}`) ||
268
+ tree.exists(`vitest.projects.${ext}`))) {
269
+ tree.write('vitest.workspace.mts', `export default [${projectGlobs}];`);
261
270
  }
262
271
  }
263
272
  if (!schema.skipFormat) {
@@ -0,0 +1,3 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ export default function useImportMetaDirname(tree: Tree): Promise<void>;
3
+ export declare function rewriteDirname(source: string): string;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = useImportMetaDirname;
4
+ exports.rewriteDirname = rewriteDirname;
5
+ const devkit_1 = require("@nx/devkit");
6
+ // Only ESM-only extensions. A `.ts`/`.js` config can still be loaded as CJS,
7
+ // where `import.meta` is a syntax error.
8
+ const CONFIG_FILE_PATTERN = /(^|\/)(vite|vitest)\.config\.(mts|mjs)$/;
9
+ let ts;
10
+ async function useImportMetaDirname(tree) {
11
+ let touchedCount = 0;
12
+ (0, devkit_1.visitNotIgnoredFiles)(tree, '.', (filePath) => {
13
+ if (!CONFIG_FILE_PATTERN.test(filePath)) {
14
+ return;
15
+ }
16
+ const original = tree.read(filePath, 'utf-8');
17
+ if (!original?.includes('__dirname')) {
18
+ return;
19
+ }
20
+ const updated = rewriteDirname(original);
21
+ if (updated !== original) {
22
+ tree.write(filePath, updated);
23
+ touchedCount += 1;
24
+ }
25
+ });
26
+ if (touchedCount > 0) {
27
+ devkit_1.logger.info(`Replaced \`__dirname\` with \`import.meta.dirname\` in ${touchedCount} Vite config file(s).`);
28
+ }
29
+ await (0, devkit_1.formatFiles)(tree);
30
+ }
31
+ function rewriteDirname(source) {
32
+ ts ??= (0, devkit_1.ensurePackage)('typescript', '*');
33
+ const sourceFile = ts.createSourceFile('tmp.mts', source, ts.ScriptTarget.Latest,
34
+ /* setParentNodes */ true, ts.ScriptKind.TS);
35
+ // A config TypeScript can only error-recover on may not mean what its AST
36
+ // says, so leave it for a human rather than rewrite it blind.
37
+ if (sourceFile.parseDiagnostics?.length) {
38
+ return source;
39
+ }
40
+ const references = [];
41
+ let bailOut = false;
42
+ const visit = (node) => {
43
+ if (ts.isIdentifier(node) && node.text === '__dirname') {
44
+ const kind = classify(node);
45
+ if (kind === 'bail') {
46
+ bailOut = true;
47
+ }
48
+ else if (kind === 'reference') {
49
+ references.push(node);
50
+ }
51
+ }
52
+ ts.forEachChild(node, visit);
53
+ };
54
+ visit(sourceFile);
55
+ if (bailOut || references.length === 0) {
56
+ return source;
57
+ }
58
+ let updated = source;
59
+ for (const node of references.reverse()) {
60
+ const start = node.getStart(sourceFile);
61
+ updated =
62
+ updated.slice(0, start) +
63
+ 'import.meta.dirname' +
64
+ updated.slice(node.getEnd());
65
+ }
66
+ return updated;
67
+ }
68
+ /**
69
+ * `bail` abandons the whole file: something binds `__dirname` in scope, so the
70
+ * identifier no longer means the CJS global, or it is a shorthand property
71
+ * where key and value are one token. `skip` leaves a single identifier alone.
72
+ *
73
+ * The name-position test is inverted on purpose - anything sitting in a
74
+ * parent's `name` or `propertyName` slot is excluded by default, so node kinds
75
+ * nobody enumerated (class fields, accessors, enum members) cannot be rewritten
76
+ * into invalid syntax.
77
+ */
78
+ function classify(node) {
79
+ const parent = node.parent;
80
+ if (!parent) {
81
+ return 'reference';
82
+ }
83
+ if (ts.isShorthandPropertyAssignment(parent)) {
84
+ return 'bail';
85
+ }
86
+ if (bindsDirname(parent, node)) {
87
+ return 'bail';
88
+ }
89
+ if (parent.name === node || parent.propertyName === node) {
90
+ return 'skip';
91
+ }
92
+ return 'reference';
93
+ }
94
+ /** Declarations that put a new `__dirname` in scope, shadowing the global. */
95
+ function bindsDirname(parent, node) {
96
+ if (parent.name !== node) {
97
+ return false;
98
+ }
99
+ return (ts.isVariableDeclaration(parent) ||
100
+ ts.isParameter(parent) ||
101
+ ts.isBindingElement(parent) ||
102
+ ts.isFunctionDeclaration(parent) ||
103
+ ts.isClassDeclaration(parent) ||
104
+ ts.isImportClause(parent) ||
105
+ ts.isImportSpecifier(parent) ||
106
+ ts.isNamespaceImport(parent) ||
107
+ ts.isExportSpecifier(parent));
108
+ }
@@ -0,0 +1,36 @@
1
+ #### Replace `__dirname` with `import.meta.dirname` in Vite config files
2
+
3
+ Vite 8 warns when a config uses features that its `configLoader: 'native'` mode cannot support, and `__dirname` is one of them:
4
+
5
+ ```
6
+ (!) Your Vite config uses features that are unsupported by `configLoader: 'native'`, which is planned to become the default in a future major version of Vite:
7
+ - `__dirname` (packages/utils/vitest.config.mts:4:9). Use `import.meta.dirname` instead
8
+ ```
9
+
10
+ This migration rewrites `__dirname` to `import.meta.dirname` in every `vite.config.mts`, `vite.config.mjs`, `vitest.config.mts`, and `vitest.config.mjs` file in your workspace.
11
+
12
+ #### Sample Code Changes
13
+
14
+ ##### Before
15
+
16
+ ```ts
17
+ export default defineConfig(() => ({
18
+ root: __dirname,
19
+ }));
20
+ ```
21
+
22
+ ##### After
23
+
24
+ ```ts
25
+ export default defineConfig(() => ({
26
+ root: import.meta.dirname,
27
+ }));
28
+ ```
29
+
30
+ #### What is not rewritten
31
+
32
+ `.ts` and `.js` configs are left alone, since those extensions can still be loaded as CommonJS, where `import.meta` is a syntax error. Configs that declare their own `__dirname` (usually `const __dirname = path.dirname(fileURLToPath(import.meta.url))`) are also left alone - that idiom already works under the native config loader.
33
+
34
+ No migration renames an existing config to `.mts`, because other tooling may reference it by path. So a workspace whose config is `.ts` keeps the companion warning about ESM syntax in a CommonJS-loaded file. Rename it yourself, or set `"type": "module"` in the closest `package.json`, to clear that one. Newly generated configs use `.mts` and are unaffected.
35
+
36
+ One generated case does put `import.meta.dirname` in a `.ts` config: `@nx/nuxt` falls back to `.ts` on workspaces still using eslintrc, because the legacy `@nuxt/eslint-config` cannot parse `.mts`. Vite's default config loader bundles that file, so it works today, but the file is not loadable under `configLoader: 'native'` - its own `import` statements already make it so.
@@ -9,14 +9,25 @@ const deprecation_1 = require("./deprecation");
9
9
  const versions_1 = require("./versions");
10
10
  function addOrChangeTestTarget(tree, options, hasPlugin) {
11
11
  const nxJson = (0, devkit_1.readNxJson)(tree);
12
- hasPlugin = nxJson.plugins?.some((p) => typeof p === 'string'
13
- ? p === '@nx/vitest'
14
- : p.plugin === '@nx/vitest' || hasPlugin);
12
+ const target = options.testTarget ?? 'test';
13
+ // The plugin only infers the target names it is registered for, so a request
14
+ // for any other name still needs an explicit target.
15
+ hasPlugin ||=
16
+ nxJson.plugins?.some((p) => {
17
+ if (typeof p === 'string') {
18
+ return p === '@nx/vitest' && target === 'test';
19
+ }
20
+ if (p.plugin !== '@nx/vitest') {
21
+ return false;
22
+ }
23
+ const pluginOptions = p.options;
24
+ return ((pluginOptions?.testTargetName ?? 'test') === target ||
25
+ pluginOptions?.ciTargetName === target);
26
+ }) ?? false;
15
27
  if (hasPlugin) {
16
28
  return;
17
29
  }
18
30
  const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
19
- const target = options.testTarget ?? 'test';
20
31
  const reportsDirectory = (0, devkit_1.joinPathFragments)('coverage', project.root === '.' ? options.project : project.root);
21
32
  const testOptions = {
22
33
  reportsDirectory,
@@ -94,7 +105,7 @@ function createOrEditViteConfig(tree, options, onlyVitest, extraOptions = {}) {
94
105
  }
95
106
  }
96
107
  if (!onlyVitest && options.includeLib) {
97
- plugins.push(`dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.lib.json')${!isTsSolutionSetup ? ', pathsToAliases: false' : ''} })`);
108
+ plugins.push(`dts({ entryRoot: 'src', tsconfigPath: path.join(import.meta.dirname, 'tsconfig.lib.json')${!isTsSolutionSetup ? ', pathsToAliases: false' : ''} })`);
98
109
  }
99
110
  const reportsDirectory = isTsSolutionSetup
100
111
  ? './test-output/vitest/coverage'
@@ -164,7 +175,7 @@ ${options.inSourceTests
164
175
  ${imports.join(';\n')}${imports.length ? ';' : ''}
165
176
 
166
177
  export default defineConfig(() => ({
167
- root: __dirname,
178
+ root: import.meta.dirname,
168
179
  ${printOptions(cacheDir, plugins.length ? ` plugins: [${plugins.join(', ')}],` : '', defineOption, testOption)}
169
180
  }));
170
181
  `.replace(/\s+(?=(\n|$))/gm, '\n')
@@ -173,7 +184,7 @@ import { defineConfig } from 'vite';
173
184
  ${imports.join(';\n')}${imports.length ? ';' : ''}
174
185
 
175
186
  export default defineConfig(() => ({
176
- root: __dirname,
187
+ root: import.meta.dirname,
177
188
  ${printOptions(cacheDir, devServerOption, previewServerOption, ` plugins: [${plugins.join(', ')}],`, workerOption, buildOption, defineOption, testOption)}
178
189
  }));
179
190
  `.replace(/\s+(?=(\n|$))/gm, '\n');
package/migrations.json CHANGED
@@ -28,6 +28,12 @@
28
28
  "description": "Rename imports of `createNodesV2` from `@nx/vitest` to the canonical `createNodes` export.",
29
29
  "implementation": "./dist/src/migrations/update-23-0-0/migrate-create-nodes-v2-to-create-nodes",
30
30
  "documentation": "./dist/src/migrations/update-23-0-0/migrate-create-nodes-v2-to-create-nodes.md"
31
+ },
32
+ "update-23-2-0-use-import-meta-dirname": {
33
+ "version": "23.2.0-beta.6",
34
+ "description": "Replace `__dirname` with `import.meta.dirname` in `vite.config.mts`/`vitest.config.mts` files so they work with Vite's `configLoader: 'native'`.",
35
+ "implementation": "./dist/src/migrations/update-23-2-0/use-import-meta-dirname",
36
+ "documentation": "./dist/src/migrations/update-23-2-0/use-import-meta-dirname.md"
31
37
  }
32
38
  },
33
39
  "packageJsonUpdates": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nx/vitest",
3
3
  "description": "The Nx Plugin for Vitest to enable fast unit testing with Vitest.",
4
- "version": "23.2.0-beta.5",
4
+ "version": "23.2.0-beta.6",
5
5
  "type": "commonjs",
6
6
  "files": [
7
7
  "dist",
@@ -73,13 +73,13 @@
73
73
  "tslib": "^2.3.0",
74
74
  "semver": "^7.6.3",
75
75
  "@phenomnomnominal/tsquery": "~6.2.0",
76
- "@nx/devkit": "23.2.0-beta.5",
77
- "@nx/js": "23.2.0-beta.5"
76
+ "@nx/devkit": "23.2.0-beta.6",
77
+ "@nx/js": "23.2.0-beta.6"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "vitest": "^3.0.0 || ^4.0.0",
81
81
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0",
82
- "@nx/eslint": "23.2.0-beta.5"
82
+ "@nx/eslint": "23.2.0-beta.6"
83
83
  },
84
84
  "peerDependenciesMeta": {
85
85
  "@nx/eslint": {
@@ -93,6 +93,6 @@
93
93
  }
94
94
  },
95
95
  "devDependencies": {
96
- "nx": "23.2.0-beta.5"
96
+ "nx": "23.2.0-beta.6"
97
97
  }
98
98
  }