Skip to content

Commit

Permalink
fix(vite): tsconfig paths plugin should resolve file extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysoo committed Sep 4, 2024
1 parent dbf7c20 commit 7c79f2a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
27 changes: 27 additions & 0 deletions e2e/vite/src/vite-crystal.test.ts → e2e/vite/src/vite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
runCommandUntil,
uniq,
updateFile,
updateJson,
} from '@nx/e2e/utils';
import { ChildProcess } from 'child_process';
import { names } from '@nx/devkit';
Expand Down Expand Up @@ -158,6 +159,32 @@ describe('@nx/vite/plugin', () => {
await killProcessAndPorts(process.pid, port);
}
});

it('should support importing .js and .css files in tsconfig path', () => {
const mylib = uniq('mylib');
runCLI(
`generate @nx/react:library ${mylib} --bundler=none --unitTestRunner=vitest --directory=libs/${mylib} --project-name-and-root-format=as-provided`
);
updateFile(`libs/${mylib}/src/styles.css`, `.foo {}`);
updateFile(`libs/${mylib}/src/foo.mts`, `export const foo = 'foo';`);
updateFile(
`libs/${mylib}/src/foo.spec.ts`,
`
import styles from '~/styles.css?inline';
import { foo } from '~/foo.mjs';
test('should work', () => {
expect(styles).toBeDefined();
expect(foo).toBeDefined();
});
`
);
updateJson('tsconfig.base.json', (json) => {
json.compilerOptions.paths['~/*'] = [`libs/${mylib}/src/*`];
return json;
});

expect(() => runCLI(`test ${mylib}`)).not.toThrow();
});
});

describe('react with vitest only', () => {
Expand Down
11 changes: 9 additions & 2 deletions packages/vite/plugins/nx-tsconfig-paths.plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
workspaceRoot,
} from '@nx/devkit';
import { copyFileSync, existsSync } from 'node:fs';
import { relative, join, resolve } from 'node:path';
import { join, parse, relative, resolve } from 'node:path';
import {
loadConfig,
createMatchPath,
Expand Down Expand Up @@ -57,8 +57,13 @@ export function nxViteTsPaths(options: nxViteTsPathsOptions = {}) {
'.js',
'.jsx',
'.json',
'.mts',
'.mjs',
'.cts',
'.cjs',
'.css',
'.scss',
'.less',
];
options.mainFields ??= [['exports', '.', 'import'], 'module', 'main'];
options.buildLibsFromSource ??= true;
Expand Down Expand Up @@ -246,7 +251,9 @@ There should at least be a tsconfig.base.json or tsconfig.json in the root of th

function findFile(path: string): string {
for (const ext of options.extensions) {
const resolvedPath = resolve(path + ext);
// Support file extensions such as .css and .js in the import path.
const { dir, name } = parse(path);
const resolvedPath = resolve(dir, name + ext);
if (existsSync(resolvedPath)) {
return resolvedPath;
}
Expand Down

0 comments on commit 7c79f2a

Please sign in to comment.