|
| 1 | +import fs from "node:fs"; |
| 2 | +import path from "node:path"; |
| 3 | +import { fileURLToPath } from "node:url"; |
1 | 4 | import { svelte, vitePreprocess } from "@sveltejs/vite-plugin-svelte"; |
2 | 5 | import { optimizeImports } from "carbon-preprocess-svelte"; |
3 | 6 | 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 | +} |
4 | 47 |
|
5 | 48 | export default defineConfig({ |
6 | 49 | root: "./tests", |
7 | 50 | plugins: [svelte({ preprocess: [vitePreprocess(), optimizeImports()] })], |
8 | 51 | optimizeDeps: { |
9 | 52 | exclude: ["carbon-components-svelte", "carbon-icons-svelte"], |
10 | 53 | }, |
11 | | - resolve: { conditions: ["browser"] }, |
| 54 | + resolve: { |
| 55 | + conditions: ["browser"], |
| 56 | + alias: generateAliasesFromExports(), |
| 57 | + }, |
12 | 58 | test: { |
13 | 59 | globals: true, |
14 | 60 | environment: "jsdom", |
|
0 commit comments