-
Notifications
You must be signed in to change notification settings - Fork 343
Expand file tree
/
Copy pathcompile.ts
More file actions
102 lines (92 loc) · 2.59 KB
/
compile.ts
File metadata and controls
102 lines (92 loc) · 2.59 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { dirname, join } from 'path';
import { promises as fs } from 'fs';
import {
build as esbuild,
Plugin,
BuildOptions as EsbuildOptions,
} from 'esbuild';
import type { IdentifierOption } from './types';
import { cssFileFilter } from './filters';
import { transform } from './transform';
import { getPackageInfo } from './packageInfo';
interface VanillaExtractTransformPluginParams {
identOption?: IdentifierOption;
}
export const vanillaExtractTransformPlugin = ({
identOption,
}: VanillaExtractTransformPluginParams): Plugin => ({
name: 'vanilla-extract-filescope',
setup(build) {
const packageInfo = getPackageInfo(build.initialOptions.absWorkingDir);
build.onLoad({ filter: cssFileFilter }, async ({ path }) => {
const originalSource = await fs.readFile(path, 'utf-8');
const source = await transform({
source: originalSource,
filePath: path,
rootPath: build.initialOptions.absWorkingDir!,
packageName: packageInfo.name,
identOption:
identOption ?? (build.initialOptions.minify ? 'short' : 'debug'),
});
return {
contents: source,
loader: path.match(/\.(ts|tsx)$/i) ? 'ts' : undefined,
resolveDir: dirname(path),
};
});
},
});
export interface CompileOptions {
filePath: string;
identOption: IdentifierOption;
cwd?: string;
esbuildOptions?: Pick<
EsbuildOptions,
| 'plugins'
| 'external'
| 'define'
| 'loader'
| 'tsconfig'
| 'conditions'
| 'logLevel'
| 'logLimit'
| 'logOverride'
>;
}
export async function compile({
filePath,
identOption,
cwd = process.cwd(),
esbuildOptions,
}: CompileOptions) {
const result = await esbuild({
entryPoints: [filePath],
metafile: true,
bundle: true,
external: ['@vanilla-extract', ...(esbuildOptions?.external ?? [])],
platform: 'node',
write: false,
plugins: [
vanillaExtractTransformPlugin({ identOption }),
...(esbuildOptions?.plugins ?? []),
],
absWorkingDir: cwd,
loader: esbuildOptions?.loader,
define: esbuildOptions?.define,
tsconfig: esbuildOptions?.tsconfig,
conditions: esbuildOptions?.conditions,
logLevel: esbuildOptions?.logLevel,
logLimit: esbuildOptions?.logLimit,
logOverride: esbuildOptions?.logOverride,
});
const { outputFiles, metafile } = result;
if (!outputFiles || outputFiles.length !== 1) {
throw new Error('Invalid child compilation');
}
return {
source: outputFiles[0].text,
watchFiles: Object.keys(metafile?.inputs || {}).map((filePath) =>
join(cwd, filePath),
),
};
}