-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathapplyServerSideProcessor.ts
More file actions
84 lines (68 loc) · 2.66 KB
/
applyServerSideProcessor.ts
File metadata and controls
84 lines (68 loc) · 2.66 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
import fs from 'fs';
import { createRequire } from 'module';
import styleSheetLoader from '../../lib/transform-styles.js';
import { checkInlineStyleEnable, checkStyleKind } from '../../utils.js';
import type { ESBuildPlugin, NormalizedRaxCompatPluginOptions, PluginAPI } from '../../typings';
const ESBuildInlineStylePlugin = (options: NormalizedRaxCompatPluginOptions): ESBuildPlugin => {
return {
name: 'esbuild-inline-style',
setup: (build) => {
build.onResolve({ filter: /\.(css|sass|scss|less)$/ }, async (args) => {
if (args.path.startsWith('~')) {
const cleanPath = args.path.slice(1);
try {
// Try to resolve as absolute path
const require = createRequire(args.importer || import.meta.url);
const resolvedPath = require.resolve(cleanPath);
return {
path: resolvedPath,
namespace: args.namespace,
};
} catch (resolveError) {
// If unable to resolve, mark as external dependency
return {
path: cleanPath,
external: true,
};
}
}
return null;
});
build.onLoad({ filter: /\.(css|sass|scss|less)$/ }, async (args) => {
if (checkInlineStyleEnable(args.path, options.inlineStyle) === false) {
return null;
}
const cssContent = await fs.promises.readFile(args.path, 'utf8');
const content = await styleSheetLoader(cssContent, args.path, checkStyleKind(args.path));
return {
contents: content,
loader: 'js',
};
});
},
};
};
export const applyServerSideStyleProcessor = (api: PluginAPI, options: NormalizedRaxCompatPluginOptions) => {
const { userConfig } = api.context;
if (!userConfig.ssr && !userConfig.ssg) {
return;
}
api.onGetConfig((config) => {
config.server ??= {};
const previousBuildOptions = config.server.buildOptions;
config.server.buildOptions = (buildOptions) => {
const currentOptions = previousBuildOptions?.(buildOptions) ?? buildOptions ?? {};
// Remove esbuild-empty-css while use inline style.
currentOptions.plugins = currentOptions.plugins?.filter(({ name }) => name !== 'esbuild-empty-css');
const cssModuleIndex = currentOptions.plugins?.findIndex(({ name }) => name === 'esbuild-css-modules') as number;
// Add custom transform for server compile.
currentOptions.plugins?.splice(
options.cssModule ? cssModuleIndex + 1 : cssModuleIndex,
0,
ESBuildInlineStylePlugin(options),
);
currentOptions.treeShaking = true;
return currentOptions;
};
});
};