Jack Hsu 4a5eb23302
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 #
2024-06-11 16:55:58 -04:00

104 lines
2.8 KiB
TypeScript

import {
createProjectGraphAsync,
formatFiles,
GeneratorCallback,
readNxJson,
runTasksInSerial,
Tree,
updateNxJson,
} 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';
export function updateNxJsonSettings(tree: Tree) {
const nxJson = readNxJson(tree);
const productionFileSet = nxJson.namedInputs?.production;
if (productionFileSet) {
productionFileSet.push(
'!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)',
'!{projectRoot}/tsconfig.spec.json'
);
nxJson.namedInputs.production = Array.from(new Set(productionFileSet));
}
const hasPlugin = nxJson.plugins?.some((p) =>
typeof p === 'string'
? p === '@nx/vite/plugin'
: p.plugin === '@nx/vite/plugin'
);
if (!hasPlugin) {
nxJson.targetDefaults ??= {};
nxJson.targetDefaults['@nx/vite:test'] ??= {};
nxJson.targetDefaults['@nx/vite:test'].cache ??= true;
nxJson.targetDefaults['@nx/vite:test'].inputs ??= [
'default',
productionFileSet ? '^production' : '^default',
];
}
updateNxJson(tree, nxJson);
}
export function initGenerator(tree: Tree, schema: InitGeneratorSchema) {
return initGeneratorInternal(tree, { addPlugin: false, ...schema });
}
export async function initGeneratorInternal(
tree: Tree,
schema: InitGeneratorSchema
) {
const nxJson = readNxJson(tree);
const addPluginDefault =
process.env.NX_ADD_PLUGINS !== 'false' &&
nxJson.useInferencePlugins !== false;
schema.addPlugin ??= addPluginDefault;
if (schema.addPlugin) {
await addPluginV1(
tree,
await createProjectGraphAsync(),
'@nx/vite/plugin',
createNodes,
{
buildTargetName: ['build', 'vite:build', 'vite-build'],
testTargetName: ['test', 'vite:test', 'vite-test'],
serveTargetName: ['serve', 'vite:serve', 'vite-serve'],
previewTargetName: ['preview', 'vite:preview', 'vite-preview'],
serveStaticTargetName: [
'serve-static',
'vite:serve-static',
'vite-serve-static',
],
},
schema.updatePackageScripts
);
}
updateNxJsonSettings(tree);
if (schema.setupPathsPlugin) {
await setupPathsPlugin(tree, { skipFormat: true });
}
const tasks: GeneratorCallback[] = [];
if (!schema.skipPackageJson) {
tasks.push(moveToDevDependencies(tree));
tasks.push(checkDependenciesInstalled(tree, schema));
}
if (!schema.skipFormat) {
await formatFiles(tree);
}
return runTasksInSerial(...tasks);
}
export default initGenerator;