-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathconfig.ts
627 lines (570 loc) · 16.4 KB
/
config.ts
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import fs from 'node:fs';
import path, { dirname, isAbsolute, join } from 'node:path';
import {
type RsbuildConfig,
type RsbuildInstance,
createRsbuild,
defineConfig as defineRsbuildConfig,
loadConfig as loadRsbuildConfig,
mergeRsbuildConfig,
} from '@rsbuild/core';
import glob from 'fast-glob';
import { DEFAULT_CONFIG_NAME, DEFAULT_EXTENSIONS } from './constant';
import type {
AutoExternal,
Format,
LibConfig,
PackageJson,
RslibConfig,
RslibConfigAsyncFn,
RslibConfigExport,
RslibConfigSyncFn,
Syntax,
} from './types';
import { getDefaultExtension } from './utils/extension';
import {
calcLongestCommonPath,
color,
getExportEntries,
isObject,
nodeBuiltInModules,
readPackageJson,
} from './utils/helper';
import { logger } from './utils/logger';
import { transformSyntaxToBrowserslist } from './utils/syntax';
/**
* This function helps you to autocomplete configuration types.
* It accepts a Rslib config object, or a function that returns a config.
*/
export function defineConfig(config: RslibConfig): RslibConfig;
export function defineConfig(config: RslibConfigSyncFn): RslibConfigSyncFn;
export function defineConfig(config: RslibConfigAsyncFn): RslibConfigAsyncFn;
export function defineConfig(config: RslibConfigExport): RslibConfigExport;
export function defineConfig(config: RslibConfigExport) {
return config;
}
const findConfig = (basePath: string): string | undefined => {
return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(fs.existsSync);
};
const resolveConfigPath = (
root: string,
customConfig?: string,
): string | null => {
if (customConfig) {
const customConfigPath = isAbsolute(customConfig)
? customConfig
: join(root, customConfig);
if (fs.existsSync(customConfigPath)) {
return customConfigPath;
}
logger.warn(`Cannot find config file: ${color.dim(customConfigPath)}\n`);
}
const configFilePath = findConfig(join(root, DEFAULT_CONFIG_NAME));
if (configFilePath) {
return configFilePath;
}
return null;
};
export async function loadConfig({
cwd = process.cwd(),
path,
envMode,
}: {
cwd?: string;
path?: string;
envMode?: string;
}): Promise<RslibConfig> {
const configFilePath = resolveConfigPath(cwd, path);
if (configFilePath) {
const { content } = await loadRsbuildConfig({
cwd: dirname(configFilePath),
path: configFilePath,
envMode,
});
return content as RslibConfig;
}
const pkgJson = readPackageJson(cwd);
if (pkgJson) {
const exportEntries = getExportEntries(pkgJson);
}
return {} as RslibConfig;
}
export const composeAutoExternalConfig = (options: {
autoExternal: AutoExternal;
pkgJson?: PackageJson;
userExternals?: NonNullable<RsbuildConfig['output']>['externals'];
}): RsbuildConfig => {
const { autoExternal, pkgJson, userExternals } = options;
if (!autoExternal) {
return {};
}
if (!pkgJson) {
logger.warn(
'autoExternal configuration will not be applied due to read package.json failed',
);
return {};
}
const externalOptions = {
dependencies: true,
peerDependencies: true,
devDependencies: false,
...(autoExternal === true ? {} : autoExternal),
};
// User externals configuration has higher priority than autoExternal
// eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
// Only handle the case where the externals type is object, string / string[] does not need to be processed, other types are too complex.
const userExternalKeys =
userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
const externals = (
['dependencies', 'peerDependencies', 'devDependencies'] as const
)
.reduce<string[]>((prev, type) => {
if (externalOptions[type]) {
return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type]!)) : prev;
}
return prev;
}, [])
.filter((name) => !userExternalKeys.includes(name));
const uniqueExternals = Array.from(new Set(externals));
return externals.length
? {
output: {
externals: [
// Exclude dependencies, e.g. `react`, `react/jsx-runtime`
...uniqueExternals.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
...uniqueExternals,
],
},
}
: {};
};
export async function createInternalRsbuildConfig(): Promise<RsbuildConfig> {
return defineRsbuildConfig({
mode: 'production',
dev: {
progressBar: false,
},
tools: {
htmlPlugin: false,
rspack: {
optimization: {
moduleIds: 'named',
},
experiments: {
rspackFuture: {
bundlerInfo: {
force: false,
},
},
},
},
},
output: {
filenameHash: false,
// TODO: easy to development at the moment
minify: false,
distPath: {
js: './',
},
},
});
}
const composeFormatConfig = (format: Format): RsbuildConfig => {
switch (format) {
case 'esm':
return {
tools: {
rspack: {
externalsType: 'module-import',
output: {
module: true,
chunkFormat: 'module',
library: {
type: 'modern-module',
},
},
module: {
parser: {
javascript: {
importMeta: false,
},
},
},
optimization: {
concatenateModules: true,
},
experiments: {
outputModule: true,
},
},
},
};
case 'cjs':
return {
tools: {
rspack: {
externalsType: 'commonjs',
output: {
iife: false,
chunkFormat: 'commonjs',
library: {
type: 'commonjs',
},
},
},
},
};
case 'umd':
return {
tools: {
rspack: {
externalsType: 'umd',
output: {
library: {
type: 'umd',
},
},
},
},
};
default:
throw new Error(`Unsupported format: ${format}`);
}
};
const composeAutoExtensionConfig = (
config: LibConfig,
autoExtension: boolean,
pkgJson?: PackageJson,
): {
config: RsbuildConfig;
jsExtension: string;
dtsExtension: string;
} => {
const { jsExtension, dtsExtension } = getDefaultExtension({
format: config.format!,
pkgJson,
autoExtension,
});
return {
config: {
output: {
filename: {
js: `[name]${jsExtension}`,
...config.output?.filename,
},
},
},
jsExtension,
dtsExtension,
};
};
const composeSyntaxConfig = (
syntax?: Syntax,
target?: string,
): RsbuildConfig => {
// Defaults to ESNext, Rslib will assume all of the latest JavaScript and CSS features are supported.
if (syntax) {
return {
tools: {
rspack: (config) => {
// TODO: Rspack should could resolve `browserslist:{query}` like webpack.
// https://webpack.js.org/configuration/target/#browserslist
// Using 'es5' as a temporary solution for compatibility.
config.target = ['es5'];
return config;
},
},
output: {
overrideBrowserslist: transformSyntaxToBrowserslist(syntax),
},
};
}
// If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
const lastTargetVersions = {
node: ['last 1 node versions'],
web: [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Edge versions',
'last 1 Safari versions',
'last 1 ios_saf versions',
'not dead',
],
};
return {
tools: {
rspack: (config) => {
config.target = ['es2022'];
return config;
},
},
output: {
overrideBrowserslist:
target === 'web'
? lastTargetVersions.web
: target === 'node'
? lastTargetVersions.node
: [...lastTargetVersions.node, ...lastTargetVersions.web],
},
};
};
const composeEntryConfig = async (
entries: NonNullable<RsbuildConfig['source']>['entry'],
bundle: LibConfig['bundle'],
root: string,
): Promise<RsbuildConfig> => {
if (!entries) {
return {};
}
if (bundle !== false) {
return {
source: {
entry: entries,
},
};
}
// In bundleless mode, resolve glob patterns and convert them to entry object.
const resolvedEntries: Record<string, string> = {};
for (const key of Object.keys(entries)) {
const entry = entries[key];
// Entries in bundleless mode could be:
// 1. A string of glob pattern: { entry: { index: 'src/*.ts' } }
// 2. An array of glob patterns: { entry: { index: ['src/*.ts', 'src/*.tsx'] } }
// Not supported for now: entry description object
const entryFiles = Array.isArray(entry)
? entry
: typeof entry === 'string'
? [entry]
: null;
if (!entryFiles) {
throw new Error(
'Entry can only be a string or an array of strings for now',
);
}
// Turn entries in array into each separate entry.
const resolvedEntryFiles = await glob(entryFiles, {
cwd: root,
});
if (resolvedEntryFiles.length === 0) {
throw new Error(`Cannot find ${resolvedEntryFiles}`);
}
// Similar to `rootDir` in tsconfig and `outbase` in esbuild.
const lcp = await calcLongestCommonPath(resolvedEntryFiles);
// Using the longest common path of all non-declaration input files by default.
const outBase = lcp === null ? root : lcp;
for (const file of resolvedEntryFiles) {
const { dir, name } = path.parse(path.relative(outBase, file));
// Entry filename contains nested path to preserve source directory structure.
const entryFileName = path.join(dir, name);
resolvedEntries[entryFileName] = file;
}
}
return {
source: {
entry: resolvedEntries,
},
};
};
const composeBundleConfig = (
jsExtension: string,
bundle = true,
): RsbuildConfig => {
if (bundle) return {};
return {
output: {
externals: [
(data: any, callback: any) => {
// Issuer is not empty string when the module is imported by another module.
// Prevent from externalizing entry modules here.
if (data.contextInfo.issuer) {
// Node.js ECMAScript module loader does no extension searching.
// So we add a file extension here when data.request is a relative path
return callback(
null,
data.request[0] === '.'
? `${data.request}${jsExtension}`
: data.request,
);
}
callback();
},
],
},
};
};
const composeDtsConfig = async (
libConfig: LibConfig,
dtsExtension: string,
): Promise<RsbuildConfig> => {
const { dts, bundle, output, autoExternal } = libConfig;
if (dts === false || dts === undefined) return {};
const { pluginDts } = await import('rsbuild-plugin-dts');
return {
plugins: [
pluginDts({
bundle: dts?.bundle ?? bundle,
distPath: dts?.distPath ?? output?.distPath?.root ?? './dist',
abortOnError: dts?.abortOnError ?? true,
dtsExtension,
autoExternal,
}),
],
};
};
const composeTargetConfig = (target = 'web'): RsbuildConfig => {
switch (target) {
case 'web':
return {
tools: {
rspack: {
target: ['web'],
},
},
};
case 'node':
return {
tools: {
rspack: {
target: ['node'],
// "__dirname" and "__filename" shims will automatically be enabled when `output.module` is `true`,
// and leave them as-is in the rest of the cases.
// { node: { __dirname: ..., __filename: ... } }
},
},
output: {
// When output.target is 'node', Node.js's built-in will be treated as externals of type `node-commonjs`.
// Simply override the built-in modules to make them external.
// https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L81
externals: nodeBuiltInModules,
target: 'node',
},
};
case 'neutral':
return {
tools: {
rspack: {
target: ['web', 'node'],
},
},
};
default:
throw new Error(`Unsupported platform: ${target}`);
}
};
async function composeLibRsbuildConfig(
libConfig: LibConfig,
rsbuildConfig: RsbuildConfig,
configPath: string,
) {
const config = mergeRsbuildConfig<LibConfig>(rsbuildConfig, libConfig);
const rootPath = dirname(configPath);
const pkgJson = readPackageJson(rootPath);
const { format, autoExtension = true, autoExternal = true } = config;
const formatConfig = composeFormatConfig(format!);
const {
config: autoExtensionConfig,
jsExtension,
dtsExtension,
} = composeAutoExtensionConfig(config, autoExtension, pkgJson);
const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
const targetConfig = composeTargetConfig(config.output?.target);
const syntaxConfig = composeSyntaxConfig(
config.output?.syntax,
config.output?.target,
);
const autoExternalConfig = composeAutoExternalConfig({
autoExternal,
pkgJson,
userExternals: rsbuildConfig.output?.externals,
});
const entryConfig = await composeEntryConfig(
config.source?.entry,
config.bundle,
dirname(configPath),
);
const dtsConfig = await composeDtsConfig(config, dtsExtension);
return mergeRsbuildConfig(
formatConfig,
autoExtensionConfig,
autoExternalConfig,
syntaxConfig,
bundleConfig,
targetConfig,
entryConfig,
dtsConfig,
);
}
export async function composeCreateRsbuildConfig(
rslibConfig: RslibConfig,
path?: string,
): Promise<{ format: Format; config: RsbuildConfig }[]> {
const internalRsbuildConfig = await createInternalRsbuildConfig();
const configPath = path ?? rslibConfig._privateMeta?.configFilePath!;
const { lib: libConfigsArray, ...sharedRsbuildConfig } = rslibConfig;
if (!libConfigsArray) {
throw new Error(
`Expect lib field to be an array, but got ${libConfigsArray}.`,
);
}
const libConfigPromises = libConfigsArray.map(async (libConfig) => {
const { format, ...overrideRsbuildConfig } = libConfig;
const baseRsbuildConfig = mergeRsbuildConfig(
sharedRsbuildConfig,
overrideRsbuildConfig,
);
// Merge the configuration of each environment based on the shared Rsbuild
// configuration and Lib configuration in the settings.
const libRsbuildConfig = await composeLibRsbuildConfig(
libConfig,
baseRsbuildConfig,
configPath,
);
// Reset certain fields because they will be completely overridden by the upcoming merge.
// We don't want to retain them in the final configuration.
// The reset process should occur after merging the library configuration.
baseRsbuildConfig.source ??= {};
baseRsbuildConfig.source.entry = {};
return {
format: format!,
config: mergeRsbuildConfig(
baseRsbuildConfig,
libRsbuildConfig,
// Merge order matters, keep `internalRsbuildConfig` at the last position
// to ensure that the internal config is not overridden by user's config.
internalRsbuildConfig,
),
};
});
const composedRsbuildConfig = await Promise.all(libConfigPromises);
return composedRsbuildConfig;
}
export async function initRsbuild(
rslibConfig: RslibConfig,
): Promise<RsbuildInstance> {
const rsbuildConfigObject = await composeCreateRsbuildConfig(rslibConfig);
const environments: RsbuildConfig['environments'] = {};
const formatCount: Record<Format, number> = rsbuildConfigObject.reduce(
(acc, { format }) => {
acc[format] = (acc[format] ?? 0) + 1;
return acc;
},
{} as Record<Format, number>,
);
const formatIndex: Record<Format, number> = {
esm: 0,
cjs: 0,
umd: 0,
};
for (const { format, config } of rsbuildConfigObject) {
const currentFormatCount = formatCount[format];
const currentFormatIndex = formatIndex[format]++;
environments[
currentFormatCount === 1 ? format : `${format}${currentFormatIndex}`
] = config;
}
return createRsbuild({
rsbuildConfig: {
environments,
},
});
}