Skip to content

Commit

Permalink
feat(vite): add tsconfig paths resolution plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
barbados-clemens committed Jun 28, 2023
1 parent 7d15e0c commit 948e075
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"dotenv": "~10.0.0",
"enquirer": "~2.3.6",
"@nx/devkit": "file:../devkit",
"@nx/js": "file:../js"
"@nx/js": "file:../js",
"tsconfig-paths": "^4.1.2"
},
"peerDependencies": {
"vite": "^4.3.4",
Expand Down
35 changes: 35 additions & 0 deletions packages/vite/plugins/nx-tsconfig-paths.plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { workspaceRoot } from '@nx/devkit';
import { relative, join, resolve } from 'node:path';
import { loadConfig, createMatchPath, MatchPath } from 'tsconfig-paths';

export function nxViteTsPaths() {
let matchTsPath: MatchPath;

return {
name: 'nx-vite-ts-paths',
configResolved(config: any) {
const projectRoot = config.root;
const tsConfigGeneratedPath = join(
'tmp',
relative(workspaceRoot, projectRoot)
);

const tmpRoot = resolve(workspaceRoot, tsConfigGeneratedPath);
// TODO(caleb): fallback to root level tsconfig file if generated doesn't not exist
const tsConfigPath = resolve(tmpRoot, 'tsconfig.generated.json');
const parsed = loadConfig(tsConfigPath);

if (parsed.resultType === 'failed') {
throw new Error('unable to load tsconfig');
}
matchTsPath = createMatchPath(parsed.absoluteBaseUrl, parsed.paths, [
// TODO(caleb): should there be any other places to match?
['exports', '.', 'import'],
]);
},
resolveId(source: string) {
const resolvedFile = matchTsPath(source);
return resolvedFile;
},
};
}

0 comments on commit 948e075

Please sign in to comment.