fix(bundling): vite init generator supports updating vite projects to use workspace libraries (#26503)

This PR adds a `@nx/vite:setup-paths-plugin` generator to add
`nxViteTsPaths` plugin to all vite config files in the workspace. This
can also be used with init/add as follows:

```shell
nx add @nx/vite --setupPathsPlugin
nx g @nx/vite:init --setupPathsPlugin
```

Which takes a config such as:

```ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})
```

And updates it to:

```ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';

export default defineConfig({
  plugins: [react(), nxViteTsPaths()],
})
```

Taking into account ESM (default) and CJS (deprecated).

<!-- Please make sure you have read the submission guidelines before
posting an PR -->
<!--
https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr
-->

<!-- Please make sure that your commit message follows our format -->
<!-- Example: `fix(nx): must begin with lowercase` -->

## Current Behavior
<!-- This is the behavior we have today -->

## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #
This commit is contained in:
Jack Hsu 2024-06-11 16:55:58 -04:00 committed by GitHub
parent 0a4551c2f3
commit 4a5eb23302
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 376 additions and 6 deletions

View File

@ -9577,6 +9577,14 @@
"isExternal": false,
"disableCollapsible": false
},
{
"id": "setup-paths-plugin",
"path": "/nx-api/vite/generators/setup-paths-plugin",
"name": "setup-paths-plugin",
"children": [],
"isExternal": false,
"disableCollapsible": false
},
{
"id": "vitest",
"path": "/nx-api/vite/generators/vitest",

View File

@ -2950,8 +2950,17 @@
"path": "/nx-api/vite/generators/configuration",
"type": "generator"
},
"/nx-api/vite/generators/setup-paths-plugin": {
"description": "Sets up the nxViteTsPaths plugin to enable support for workspace libraries.",
"file": "generated/packages/vite/generators/setup-paths-plugin.json",
"hidden": false,
"name": "setup-paths-plugin",
"originalFilePath": "/packages/vite/src/generators/setup-paths-plugin/schema.json",
"path": "/nx-api/vite/generators/setup-paths-plugin",
"type": "generator"
},
"/nx-api/vite/generators/vitest": {
"description": "Generate a vitest configuration",
"description": "Generate a vitest configuration.",
"file": "generated/packages/vite/generators/vitest.json",
"hidden": false,
"name": "vitest",

View File

@ -2919,7 +2919,16 @@
"type": "generator"
},
{
"description": "Generate a vitest configuration",
"description": "Sets up the nxViteTsPaths plugin to enable support for workspace libraries.",
"file": "generated/packages/vite/generators/setup-paths-plugin.json",
"hidden": false,
"name": "setup-paths-plugin",
"originalFilePath": "/packages/vite/src/generators/setup-paths-plugin/schema.json",
"path": "vite/generators/setup-paths-plugin",
"type": "generator"
},
{
"description": "Generate a vitest configuration.",
"file": "generated/packages/vite/generators/vitest.json",
"hidden": false,
"name": "vitest",

View File

@ -39,6 +39,12 @@ In any Nx workspace, you can install `@nx/vite` by running the following command
nx add @nx/vite
```
You can also pass the `--setupPathsPlugin` flag to add [`nxViteTsPaths` plugin](/recipes/vite/configure-vite#typescript-paths), so your projects can use workspace libraries.
```shell {% skipRescope=true %}
nx add @nx/vite --setupPathsPlugin
```
This will install the correct version of `@nx/vite`.
### How @nx/vite Infers Tasks

View File

@ -18,6 +18,11 @@
"type": "boolean",
"default": false
},
"setupPathsPlugin": {
"type": "boolean",
"description": "Updates vite config files to enable support for workspace libraries via the nxViteTsPaths plugin.",
"default": false
},
"keepExistingVersions": {
"type": "boolean",
"x-priority": "internal",

View File

@ -0,0 +1,25 @@
{
"name": "setup-paths-plugin",
"factory": "./src/generators/setup-paths-plugin/setup-paths-plugin",
"schema": {
"cli": "nx",
"title": "Sets up the nxViteTsPaths plugin.",
"description": "Updates vite config files to enable support for workspace libraries via the nxViteTsPaths plugin.",
"$id": "setup-paths-plugin-vite-plugin",
"type": "object",
"properties": {
"skipFormat": {
"description": "Skip formatting files.",
"type": "boolean",
"default": false
}
},
"presets": []
},
"description": "Sets up the nxViteTsPaths plugin to enable support for workspace libraries.",
"implementation": "/packages/vite/src/generators/setup-paths-plugin/setup-paths-plugin.ts",
"aliases": [],
"hidden": false,
"path": "/packages/vite/src/generators/setup-paths-plugin/schema.json",
"type": "generator"
}

View File

@ -56,7 +56,7 @@
"required": ["project"],
"presets": []
},
"description": "Generate a vitest configuration",
"description": "Generate a vitest configuration.",
"implementation": "/packages/vite/src/generators/vitest/vitest-generator#vitestGeneratorInternal.ts",
"aliases": [],
"hidden": false,

View File

@ -39,6 +39,12 @@ In any Nx workspace, you can install `@nx/vite` by running the following command
nx add @nx/vite
```
You can also pass the `--setupPathsPlugin` flag to add [`nxViteTsPaths` plugin](/recipes/vite/configure-vite#typescript-paths), so your projects can use workspace libraries.
```shell {% skipRescope=true %}
nx add @nx/vite --setupPathsPlugin
```
This will install the correct version of `@nx/vite`.
### How @nx/vite Infers Tasks

View File

@ -674,6 +674,7 @@
- [generators](/nx-api/vite/generators)
- [init](/nx-api/vite/generators/init)
- [configuration](/nx-api/vite/generators/configuration)
- [setup-paths-plugin](/nx-api/vite/generators/setup-paths-plugin)
- [vitest](/nx-api/vite/generators/vitest)
- [vue](/nx-api/vue)
- [documents](/nx-api/vue/documents)

View File

@ -16,10 +16,15 @@
"aliases": ["config"],
"hidden": false
},
"setup-paths-plugin": {
"factory": "./src/generators/setup-paths-plugin/setup-paths-plugin",
"schema": "./src/generators/setup-paths-plugin/schema.json",
"description": "Sets up the nxViteTsPaths plugin to enable support for workspace libraries."
},
"vitest": {
"factory": "./src/generators/vitest/vitest-generator#vitestGeneratorInternal",
"schema": "./src/generators/vitest/schema.json",
"description": "Generate a vitest configuration"
"description": "Generate a vitest configuration."
}
}
}

View File

@ -4,11 +4,13 @@ import {
ProjectGraph,
readJson,
readNxJson,
stripIndents,
Tree,
updateJson,
} from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { nxVersion } from '../../utils/versions';
import { initGenerator } from './init';
let projectGraph: ProjectGraph;
jest.mock('@nx/devkit', () => ({
@ -18,8 +20,6 @@ jest.mock('@nx/devkit', () => ({
}),
}));
import { initGenerator } from './init';
describe('@nx/vite:init', () => {
let tree: Tree;
@ -99,4 +99,31 @@ describe('@nx/vite:init', () => {
`);
});
});
it('should add nxViteTsPaths plugin to vite config files when setupPathsPlugin is set to true', async () => {
tree.write(
'proj/vite.config.ts',
stripIndents`
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})`
);
await initGenerator(tree, {
addPlugin: true,
setupPathsPlugin: true,
});
expect(tree.read('proj/vite.config.ts').toString()).toMatchInlineSnapshot(`
"import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
plugins: [react(), nxViteTsPaths()],
});
"
`);
});
});

View File

@ -9,6 +9,7 @@ import {
} from '@nx/devkit';
import { addPluginV1 } from '@nx/devkit/src/utils/add-plugin';
import { setupPathsPlugin } from '../setup-paths-plugin/setup-paths-plugin';
import { createNodes } from '../../plugins/plugin';
import { InitGeneratorSchema } from './schema';
import { checkDependenciesInstalled, moveToDevDependencies } from './lib/utils';
@ -82,6 +83,10 @@ export async function initGeneratorInternal(
updateNxJsonSettings(tree);
if (schema.setupPathsPlugin) {
await setupPathsPlugin(tree, { skipFormat: true });
}
const tasks: GeneratorCallback[] = [];
if (!schema.skipPackageJson) {
tasks.push(moveToDevDependencies(tree));

View File

@ -1,5 +1,6 @@
export interface InitGeneratorSchema {
skipFormat?: boolean;
setupPathsPlugin?: boolean;
skipPackageJson?: boolean;
keepExistingVersions?: boolean;
updatePackageScripts?: boolean;

View File

@ -15,6 +15,11 @@
"type": "boolean",
"default": false
},
"setupPathsPlugin": {
"type": "boolean",
"description": "Updates vite config files to enable support for workspace libraries via the nxViteTsPaths plugin.",
"default": false
},
"keepExistingVersions": {
"type": "boolean",
"x-priority": "internal",

View File

@ -0,0 +1,9 @@
export interface InitGeneratorSchema {
skipFormat?: boolean;
addTsPathsPlugin?: boolean;
skipPackageJson?: boolean;
keepExistingVersions?: boolean;
updatePackageScripts?: boolean;
addPlugin?: boolean;
vitestOnly?: boolean;
}

View File

@ -0,0 +1,14 @@
{
"cli": "nx",
"title": "Sets up the nxViteTsPaths plugin.",
"description": "Updates vite config files to enable support for workspace libraries via the nxViteTsPaths plugin.",
"$id": "setup-paths-plugin-vite-plugin",
"type": "object",
"properties": {
"skipFormat": {
"description": "Skip formatting files.",
"type": "boolean",
"default": false
}
}
}

View File

@ -0,0 +1,79 @@
import { ProjectGraph, stripIndents, Tree } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { setupPathsPlugin } from './setup-paths-plugin';
let projectGraph: ProjectGraph;
jest.mock('@nx/devkit', () => ({
...jest.requireActual<any>('@nx/devkit'),
createProjectGraphAsync: jest.fn().mockImplementation(async () => {
return projectGraph;
}),
}));
describe('@nx/vite:init', () => {
let tree: Tree;
beforeEach(() => {
tree = createTreeWithEmptyWorkspace();
projectGraph = {
nodes: {},
dependencies: {},
};
});
it('should add nxViteTsPaths plugin to vite config files', async () => {
tree.write(
'proj1/vite.config.ts',
stripIndents`
import { defineConfig } from 'vite';
export default defineConfig({});`
);
tree.write(
'proj2/vite.config.ts',
stripIndents`
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})`
);
tree.write(
'proj3/vite.config.cts',
stripIndents`
const { defineConfig } = require('vite');
const react = require('@vitejs/plugin-react');
module.exports = defineConfig({
plugins: [react()],
});
`
);
await setupPathsPlugin(tree, {});
expect(tree.read('proj1/vite.config.ts').toString()).toMatchInlineSnapshot(`
"import { defineConfig } from 'vite';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({ plugins: [nxViteTsPaths()] });
"
`);
expect(tree.read('proj2/vite.config.ts').toString()).toMatchInlineSnapshot(`
"import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
plugins: [react(), nxViteTsPaths()],
});
"
`);
expect(tree.read('proj3/vite.config.cts').toString())
.toMatchInlineSnapshot(`
"const { nxViteTsPaths } = require('@nx/vite/plugins/nx-tsconfig-paths.plugin');
const { defineConfig } = require('vite');
const react = require('@vitejs/plugin-react');
module.exports = defineConfig({
plugins: [react(), nxViteTsPaths()],
});
"
`);
});
});

View File

@ -0,0 +1,156 @@
import {
applyChangesToString,
ChangeType,
formatFiles,
globAsync,
Tree,
} from '@nx/devkit';
import type { ArrayLiteralExpression, Node } from 'typescript';
export async function setupPathsPlugin(
tree: Tree,
schema: { skipFormat?: boolean }
) {
const files = await globAsync(tree, [
'**/vite.config.{js,ts,mjs,mts,cjs,cts}',
]);
for (const file of files) {
ensureImportExists(tree, file);
ensurePluginAdded(tree, file);
}
if (!schema.skipFormat) {
await formatFiles(tree);
}
}
function ensureImportExists(tree, file) {
const { tsquery } = require('@phenomnomnominal/tsquery');
let content = tree.read(file, 'utf-8');
const ast = tsquery.ast(content);
const allImports = tsquery.query(ast, 'ImportDeclaration');
if (allImports.length) {
const lastImport = allImports[allImports.length - 1];
tree.write(
file,
applyChangesToString(content, [
{
type: ChangeType.Insert,
index: lastImport.end + 1,
text: `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\n`,
},
])
);
} else {
if (file.endsWith('.cts') || file.endsWith('.cjs')) {
tree.write(
file,
applyChangesToString(content, [
{
type: ChangeType.Insert,
index: 0,
text: `const { nxViteTsPaths } = require('@nx/vite/plugins/nx-tsconfig-paths.plugin');\n`,
},
])
);
} else {
tree.write(
file,
applyChangesToString(content, [
{
type: ChangeType.Insert,
index: 0,
text: `import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';\n`,
},
])
);
}
}
}
function ensurePluginAdded(tree, file) {
const { tsquery } = require('@phenomnomnominal/tsquery');
const content = tree.read(file, 'utf-8');
const ast = tsquery.ast(content);
const foundDefineConfig = tsquery.query(
ast,
'CallExpression:has(Identifier[name="defineConfig"])'
);
if (!foundDefineConfig.length) return content;
// Do not update defineConfig if it has an arrow function since it can be tricky and error-prone.
const defineUsingArrowFunction = tsquery.query(
foundDefineConfig[0],
'ArrowFunction'
);
if (defineUsingArrowFunction.length) return content;
const propertyAssignments = tsquery.query(
foundDefineConfig[0],
'PropertyAssignment'
);
if (propertyAssignments.length) {
const pluginsNode = tsquery.query(
foundDefineConfig[0],
'PropertyAssignment:has(Identifier[name="plugins"])'
);
if (pluginsNode.length) {
const updated = tsquery.replace(
content,
'PropertyAssignment:has(Identifier[name="plugins"])',
(node: Node) => {
const found = tsquery.query(
node,
'ArrayLiteralExpression'
) as ArrayLiteralExpression[];
let updatedPluginsString = '';
const existingPluginNodes = found?.[0].elements ?? [];
for (const plugin of existingPluginNodes) {
updatedPluginsString += `${plugin.getText()},`;
}
if (
!existingPluginNodes?.some((node: Node) =>
node.getText().includes('nxViteTsPaths')
)
) {
updatedPluginsString += ` nxViteTsPaths(),`;
}
return `plugins: [${updatedPluginsString}]`;
}
);
tree.write(file, updated);
} else {
tree.write(
file,
applyChangesToString(content, [
{
type: ChangeType.Insert,
index: propertyAssignments[0].getStart(),
text: `plugins: [nxViteTsPaths()],
`,
},
])
);
}
} else {
tree.write(
file,
applyChangesToString(content, [
{
type: ChangeType.Insert,
index: foundDefineConfig[0].getStart() + 14, // length of "defineConfig(" + 1
text: `plugins: [nxViteTsPaths()],`,
},
])
);
}
}
export default setupPathsPlugin;