-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathenvironmentDefaults.ts
More file actions
101 lines (94 loc) · 3.05 KB
/
Copy pathenvironmentDefaults.ts
File metadata and controls
101 lines (94 loc) · 3.05 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
import { join } from 'node:path';
import type { RsbuildConfig, RsbuildPlugin } from '@rsbuild/core';
import {
SERVICE_WORKER_ENVIRONMENT_NAME,
getBrowserslistWithDefault,
} from '../shared/utils';
import type { DistPath } from '../types';
export const pluginEnvironmentDefaults = (
distPath: DistPath = {},
): RsbuildPlugin => ({
name: 'builder:environment-defaults-plugin',
setup(api) {
api.modifyRsbuildConfig((config, { mergeRsbuildConfig }) => {
const compatConfig: RsbuildConfig = {};
if (config.environments?.[SERVICE_WORKER_ENVIRONMENT_NAME]) {
compatConfig.environments ??= {};
compatConfig.environments[SERVICE_WORKER_ENVIRONMENT_NAME] = {
output: {
polyfill: 'off',
distPath: {
root: join(distPath.root || 'dist', distPath.worker || 'worker'),
js: '',
css: '',
jsAsync: '',
cssAsync: '',
},
filename: {
js: '[name].js',
},
},
};
}
if (config.environments?.server) {
compatConfig.environments ??= {};
compatConfig.environments.server = {
output: {
// no need to emit assets for SSR bundles
emitAssets: false,
distPath: {
root: join(distPath.root || 'dist', distPath.server || 'bundles'),
js: '',
css: '',
jsAsync: '',
cssAsync: '',
},
},
};
}
return compatConfig.environments
? mergeRsbuildConfig(compatConfig, config)
: config;
});
// ensure environment order to avoid match unexpected environment resources
// https://github.com/web-infra-dev/rsbuild/issues/2956
api.modifyRsbuildConfig({
handler: config => {
const environmentNameOrder = ['client', 'server', 'workerSSR'];
config.environments = Object.fromEntries(
Object.entries(config.environments!).sort((a1, a2) =>
environmentNameOrder.includes(a1[0])
? environmentNameOrder.indexOf(a1[0]) -
environmentNameOrder.indexOf(a2[0])
: 1,
),
);
},
order: 'post',
});
api.modifyEnvironmentConfig(async (config, { name }) => {
config.output.overrideBrowserslist ??= await getBrowserslistWithDefault(
api.context.rootPath,
config,
name === SERVICE_WORKER_ENVIRONMENT_NAME
? 'node'
: config.output.target,
);
});
api.modifyBundlerChain(async (chain, { environment }) => {
const isServiceWorker =
environment.name === SERVICE_WORKER_ENVIRONMENT_NAME;
if (isServiceWorker && chain.output.get('module') === true) {
chain.output.library({
...(chain.output.get('library') || {}),
type: 'module',
});
} else if (isServiceWorker) {
chain.output.library({
...(chain.output.get('library') || {}),
type: 'commonjs2',
});
}
});
},
});