Skip to content

Commit

Permalink
fix(vite): setup-paths-plugin should only register import once
Browse files Browse the repository at this point in the history
  • Loading branch information
Coly010 committed Jun 25, 2024
1 parent 6ebf676 commit 40dd3cf
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,62 @@ describe('@nx/vite:init', () => {
"
`);
});

it('should not add nxViteTsPaths plugin to vite config files when it exists', async () => {
tree.write(
'proj1/vite.config.ts',
stripIndents`
import { defineConfig } from 'vite';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
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');
const { nxViteTsPaths } = require('@nx/vite/plugins/nx-tsconfig-paths.plugin');
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 { defineConfig } = require('vite');
const react = require('@vitejs/plugin-react');
const { nxViteTsPaths } = require('@nx/vite/plugins/nx-tsconfig-paths.plugin');
module.exports = defineConfig({
plugins: [react(), nxViteTsPaths()],
});
"
`);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@ export async function setupPathsPlugin(
}
}

function ensureImportExists(tree, file) {
function ensureImportExists(tree: Tree, file: string) {
const { tsquery } = require('@phenomnomnominal/tsquery');
let content = tree.read(file, 'utf-8');
const ast = tsquery.ast(content);
const allImports = tsquery.query(ast, 'ImportDeclaration');
if (content.includes('@nx/vite/plugins/nx-tsconfig-paths.plugin')) {
return;
}
if (allImports.length) {
const lastImport = allImports[allImports.length - 1];
tree.write(
Expand Down

0 comments on commit 40dd3cf

Please sign in to comment.