-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvite.shared.ts
More file actions
69 lines (57 loc) · 2.13 KB
/
vite.shared.ts
File metadata and controls
69 lines (57 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { readFileSync } from 'node:fs';
import path from 'node:path';
import type { UserConfig } from 'vite';
export interface SharedViteOptions {
entry?: string | Record<string, string>;
esbuild?: { jsx: string; jsxImportSource: string };
vanillaExtract?: boolean;
}
const BASE_EXTERNALS = ['react', 'react-dom', 'react/jsx-runtime'];
export async function createViteConfig(options: SharedViteOptions = {}): Promise<UserConfig> {
const { entry = 'src/index.ts', vanillaExtract = true, esbuild } = options;
const dts = (await import('vite-plugin-dts')).default;
const plugins: UserConfig['plugins'] = [];
if (vanillaExtract) {
const { vanillaExtractPlugin } = await import('@vanilla-extract/vite-plugin');
plugins.push(vanillaExtractPlugin());
}
plugins.push(dts({ entryRoot: 'src', outDir: 'dist', tsconfigPath: './tsconfig.json' }));
const cwd = process.cwd();
const isMap = typeof entry !== 'string';
const libEntry = isMap
? Object.fromEntries(Object.entries(entry).map(([k, v]) => [k, path.resolve(cwd, v)]))
: path.resolve(cwd, entry);
const fileName = isMap ? (_: string, name: string) => `${name}.mjs` : () => 'index.mjs';
const pkg = JSON.parse(readFileSync(path.resolve(cwd, 'package.json'), 'utf8'));
const depNames = new Set([
...BASE_EXTERNALS,
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {}),
]);
const rollupExternal = (id: string) => {
if (id[0] === '.' || id[0] === '/' || id[0] === '\0') return false;
if (depNames.has(id)) return true;
const slashIdx = id.indexOf('/');
if (slashIdx > 0) {
const pkgName =
id[0] === '@' ? id.slice(0, id.indexOf('/', slashIdx + 1)) : id.slice(0, slashIdx);
return pkgName ? depNames.has(pkgName) : false;
}
return false;
};
return {
plugins,
...(esbuild && { esbuild }),
build: {
lib: { entry: libEntry, formats: ['es'], fileName },
rollupOptions: {
external: rollupExternal,
output: { preserveModules: false },
},
cssCodeSplit: false,
minify: false,
cssMinify: true,
target: 'es2020',
},
};
}