Skip to content

Commit 3c2265f

Browse files
committed
test: configure vite resolve.alias for component paths
1 parent 36d71df commit 3c2265f

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

vite.config.ts

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,60 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { fileURLToPath } from "node:url";
14
import { svelte, vitePreprocess } from "@sveltejs/vite-plugin-svelte";
25
import { optimizeImports } from "carbon-preprocess-svelte";
36
import { defineConfig } from "vitest/config";
7+
import pkg from "./package.json";
8+
9+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
10+
11+
/**
12+
* Generates Vite aliases from package.json exports for component subpath imports.
13+
* Resolves imports like `carbon-components-svelte/Theme/Theme.svelte` to
14+
* `./src/Theme/Theme.svelte` since these subpaths aren't in package.json
15+
* exports and Vite needs runtime resolution (tsconfig only handles types).
16+
*/
17+
function generateAliasesFromExports() {
18+
const aliases: Record<string, string> = {};
19+
const exports = pkg.exports;
20+
21+
const srcSvelteExport = exports["./src/*.svelte"];
22+
if (!srcSvelteExport) return aliases;
23+
24+
const srcDir = path.resolve(__dirname, "./src");
25+
if (!fs.existsSync(srcDir)) return aliases;
26+
27+
function scanDirectory(dir: string, basePath: string = "") {
28+
const entries = fs.readdirSync(dir, { withFileTypes: true });
29+
30+
for (const entry of entries) {
31+
const fullPath = path.join(dir, entry.name);
32+
const relativePath = path.join(basePath, entry.name);
33+
34+
if (entry.isDirectory()) {
35+
scanDirectory(fullPath, relativePath);
36+
} else if (entry.isFile() && entry.name.endsWith(".svelte")) {
37+
const importPath = relativePath;
38+
const aliasKey = `${pkg.name}/${importPath}`;
39+
aliases[aliasKey] = path.resolve(__dirname, "./src", importPath);
40+
}
41+
}
42+
}
43+
44+
scanDirectory(srcDir);
45+
return aliases;
46+
}
447

548
export default defineConfig({
649
root: "./tests",
750
plugins: [svelte({ preprocess: [vitePreprocess(), optimizeImports()] })],
851
optimizeDeps: {
952
exclude: ["carbon-components-svelte", "carbon-icons-svelte"],
1053
},
11-
resolve: { conditions: ["browser"] },
54+
resolve: {
55+
conditions: ["browser"],
56+
alias: generateAliasesFromExports(),
57+
},
1258
test: {
1359
globals: true,
1460
environment: "jsdom",

0 commit comments

Comments
 (0)