forked from clerk/javascript
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrspack.config.js
572 lines (541 loc) · 15.6 KB
/
rspack.config.js
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
//@ts-check
const rspack = require('@rspack/core');
const packageJSON = require('./package.json');
const path = require('path');
const { merge } = require('webpack-merge');
const ReactRefreshPlugin = require('@rspack/plugin-react-refresh');
const { RsdoctorRspackPlugin } = require('@rsdoctor/rspack-plugin');
const isProduction = mode => mode === 'production';
const isDevelopment = mode => !isProduction(mode);
const variants = {
clerk: 'clerk',
clerkNoRHC: 'clerk.no-rhc', // Omit Remotely Hosted Code
clerkBrowser: 'clerk.browser',
clerkHeadless: 'clerk.headless',
clerkHeadlessBrowser: 'clerk.headless.browser',
};
const variantToSourceFile = {
[variants.clerk]: './src/index.ts',
[variants.clerkNoRHC]: './src/index.ts',
[variants.clerkBrowser]: './src/index.browser.ts',
[variants.clerkHeadless]: './src/index.headless.ts',
[variants.clerkHeadlessBrowser]: './src/index.headless.browser.ts',
};
/**
*
* @param {object} config
* @param {'development'|'production'} config.mode
* @param {boolean} [config.disableRHC=false]
* @returns { import('@rspack/cli').Configuration }
*/
const common = ({ mode, disableRHC = false }) => {
return {
mode,
resolve: {
// Attempt to resolve these extensions in order
// @see https://webpack.js.org/configuration/resolve/#resolveextensions
extensions: ['.ts', '.tsx', '.mjs', '.js', '.jsx'],
},
plugins: [
new rspack.DefinePlugin({
__DEV__: isDevelopment(mode),
__PKG_VERSION__: JSON.stringify(packageJSON.version),
__PKG_NAME__: JSON.stringify(packageJSON.name),
/**
* Build time feature flags.
*/
__BUILD_FLAG_KEYLESS_UI__: isDevelopment(mode),
__BUILD_DISABLE_RHC__: JSON.stringify(disableRHC),
BUILD_ENABLE_NEW_COMPONENTS: JSON.stringify(process.env.BUILD_ENABLE_NEW_COMPONENTS),
}),
new rspack.EnvironmentPlugin({
CLERK_ENV: mode,
NODE_ENV: mode,
}),
process.env.RSDOCTOR &&
new RsdoctorRspackPlugin({
mode: process.env.RSDOCTOR === 'brief' ? 'brief' : 'normal',
disableClientServer: process.env.RSDOCTOR === 'brief',
supports: {
generateTileGraph: true,
},
}),
].filter(Boolean),
output: {
chunkFilename: `[name]_[fullhash:6]_${packageJSON.version}.js`,
},
optimization: {
splitChunks: {
cacheGroups: {
zxcvbnTSCoreVendor: {
test: /[\\/]node_modules[\\/](@zxcvbn-ts\/core|fastest-levenshtein)[\\/]/,
name: 'zxcvbn-ts-core',
chunks: 'all',
},
zxcvbnTSCommonVendor: {
test: /[\\/]node_modules[\\/](@zxcvbn-ts)[\\/](language-common)[\\/]/,
name: 'zxcvbn-common',
chunks: 'all',
},
coinbaseWalletSDKVendor: {
test: /[\\/]node_modules[\\/](@coinbase\/wallet-sdk|ieee754|preact|keccak|buffer|string_decoder|sha\.js|base64-js|safe-buffer|util-deprecate|inherits)[\\/]/,
name: 'coinbase-wallet-sdk',
chunks: 'all',
},
common: {
minChunks: 1,
name: 'ui-common',
priority: -20,
test: module =>
module.resource &&
!module.resource.includes('/ui/components') &&
!module.resource.includes('packages/elements') &&
!module.resource.includes('packages/ui'),
},
defaultVendors: {
minChunks: 1,
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: -10,
},
commonNew: {
minChunks: 2,
name: 'common-new',
chunks(chunk) {
return !!chunk.name?.startsWith('rebuild--');
},
priority: 0,
},
react: {
chunks: 'all',
test: /[\\/]node_modules[\\/](react-dom|scheduler)[\\/]/,
name: 'framework',
priority: 40,
enforce: true,
},
},
},
},
};
};
/** @type { () => (import('@rspack/core').RuleSetRule) } */
const svgLoader = () => {
return {
test: /\.svg$/,
resolve: {
fullySpecified: false,
},
use: {
loader: '@svgr/webpack',
options: {
svgo: true,
svgoConfig: {
floatPrecision: 3,
transformPrecision: 1,
plugins: ['preset-default', 'removeDimensions', 'removeStyleElement'],
},
},
},
};
};
/** @type { () => (import('@rspack/core').RuleSetRule[]) } */
const typescriptLoaderProd = () => {
return [
{
test: /\.(jsx?|tsx?)$/,
exclude: /node_modules/,
use: {
loader: 'builtin:swc-loader',
options: {
env: {
targets: packageJSON.browserslist,
},
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
externalHelpers: true,
transform: {
react: {
runtime: 'automatic',
importSource: '@emotion/react',
development: false,
refresh: false,
},
},
},
},
},
},
];
};
/** @type { () => (import('@rspack/core').RuleSetRule[]) } */
const typescriptLoaderDev = () => {
return [
{
test: /\.(jsx?|tsx?)$/,
exclude: /node_modules/,
loader: 'builtin:swc-loader',
options: {
jsc: {
target: 'esnext',
parser: {
syntax: 'typescript',
tsx: true,
},
externalHelpers: true,
transform: {
react: {
runtime: 'automatic',
importSource: '@emotion/react',
development: true,
refresh: true,
},
},
},
},
},
];
};
/**
* Used in outputs that utilize chunking, and returns a URL to the stylesheet.
* @type { () => (import('@rspack/core').RuleSetRule) }
*/
const clerkUICSSLoader = () => {
// This emits a module exporting a URL to the styles.css file.
return {
test: /packages\/ui\/dist\/styles\.css/,
type: 'asset/resource',
};
};
/**
* Used in outputs that _do not_ utilize chunking, and returns the contents of the stylesheet.
* @type { () => (import('@rspack/core').RuleSetRule) }
*/
const clerkUICSSSourceLoader = () => {
// This emits a module exporting the contents of the styles.css file.
return {
test: /packages\/ui\/dist\/styles\.css/,
type: 'asset/source',
};
};
/**
* Used for production builds that have dynamicly loaded chunks.
* @type { () => (import('@rspack/core').Configuration) }
* */
const commonForProdChunked = () => {
return {
module: {
rules: [svgLoader(), ...typescriptLoaderProd(), clerkUICSSLoader()],
},
};
};
/**
* Used for production builds that combine all files into one single file (such as for Chrome Extensions).
* @type { () => (import('@rspack/core').Configuration) }
* */
const commonForProdBundled = () => {
return {
module: {
rules: [svgLoader(), ...typescriptLoaderProd(), clerkUICSSSourceLoader()],
},
};
};
/** @type { () => (import('@rspack/core').Configuration) } */
const commonForProd = () => {
return {
devtool: false,
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
libraryTarget: 'umd',
globalObject: 'globalThis',
},
optimization: {
minimize: true,
minimizer: [
new rspack.SwcJsMinimizerRspackPlugin({
minimizerOptions: {
compress: {
unused: true,
dead_code: true,
passes: 2,
},
mangle: {
safari10: true,
},
},
}),
],
},
plugins: [
// new webpack.optimize.LimitChunkCountPlugin({
// maxChunks: 5,
// }),
// new webpack.optimize.MinChunkSizePlugin({
// minChunkSize: 10000,
// })
],
};
};
// /** @type { () => (import('webpack').Configuration) } */
// const externalsForHeadless = () => {
// return {
// externals: {
// react: 'react',
// 'react-dom': 'react-dom',
// },
// };
// };
/**
*
* @param {string} variant
* @returns {import('@rspack/core').Configuration}
*/
const entryForVariant = variant => {
return { entry: { [variant]: variantToSourceFile[variant] } };
};
/**
*
* @param {object} config
* @param {'development'|'production'} config.mode
* @param {boolean} config.analysis
* @param {object} config.env
* @returns {(import('@rspack/core').Configuration)[]}
*/
const prodConfig = ({ mode, env, analysis }) => {
const isSandbox = !!env.sandbox;
const clerkBrowser = merge(
entryForVariant(variants.clerkBrowser),
isSandbox
? {
entry: { sandbox: './sandbox/app.ts' },
plugins: [
new rspack.HtmlRspackPlugin({
minify: false,
template: './sandbox/template.html',
inject: false,
hash: true,
}),
],
}
: {},
common({ mode }),
commonForProd(),
commonForProdChunked(),
);
const clerkHeadless = merge(
entryForVariant(variants.clerkHeadless),
common({ mode }),
commonForProd(),
commonForProdChunked(),
// Disable chunking for the headless variant, since it's meant to be used in a non-browser environment and
// attempting to load chunks causes issues due to usage of a dynamic publicPath. We generally are only concerned with
// chunking in our browser bundles.
{
output: {
publicPath: '',
},
optimization: {
splitChunks: false,
},
},
// externalsForHeadless(),
);
const clerkHeadlessBrowser = merge(
entryForVariant(variants.clerkHeadlessBrowser),
common({ mode }),
commonForProd(),
commonForProdChunked(),
// externalsForHeadless(),
);
const clerkEsm = merge(entryForVariant(variants.clerk), common({ mode }), commonForProd(), commonForProdBundled(), {
experiments: {
outputModule: true,
},
output: {
filename: '[name].mjs',
libraryTarget: 'module',
},
plugins: [
// Include the lazy chunks in the bundle as well
// so that the final bundle can be imported and bundled again
// by a different bundler, eg the webpack instance used by react-scripts
new rspack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
],
optimization: {
splitChunks: false,
},
});
const clerkCjs = merge(entryForVariant(variants.clerk), common({ mode }), commonForProd(), commonForProdBundled(), {
output: {
filename: '[name].js',
libraryTarget: 'commonjs',
},
plugins: [
// Include the lazy chunks in the bundle as well
// so that the final bundle can be imported and bundled again
// by a different bundler, eg the webpack instance used by react-scripts
new rspack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
],
optimization: {
splitChunks: false,
},
});
const clerkEsmNoRHC = merge(
entryForVariant(variants.clerkNoRHC),
common({ mode, disableRHC: true }),
commonForProd(),
commonForProdBundled(),
{
experiments: {
outputModule: true,
},
output: {
filename: '[name].mjs',
libraryTarget: 'module',
},
plugins: [
// Include the lazy chunks in the bundle as well
// so that the final bundle can be imported and bundled again
// by a different bundler, eg the webpack instance used by react-scripts
new rspack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
],
optimization: {
splitChunks: false,
},
},
);
const clerkCjsNoRHC = merge(
entryForVariant(variants.clerkNoRHC),
common({ mode, disableRHC: true }),
commonForProd(),
commonForProdBundled(),
{
output: {
filename: '[name].js',
libraryTarget: 'commonjs',
},
plugins: [
// Include the lazy chunks in the bundle as well
// so that the final bundle can be imported and bundled again
// by a different bundler, eg the webpack instance used by react-scripts
new rspack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
],
optimization: {
splitChunks: false,
},
},
);
// webpack-bundle-analyzer only supports a single build, use clerkBrowser as that's the default build we serve
if (analysis) {
return [clerkBrowser];
}
return [clerkBrowser, clerkHeadless, clerkHeadlessBrowser, clerkEsm, clerkEsmNoRHC, clerkCjs, clerkCjsNoRHC];
};
/**
*
* @param {object} config
* @param {'development'|'production'} config.mode
* @param {object} config.env
* @returns
*/
const devConfig = ({ mode, env }) => {
const variant = env.variant || variants.clerkBrowser;
// accept an optional devOrigin environment option to change the origin of the dev server.
// By default we use https://js.lclclerk.com which is what our local dev proxy looks for.
const devUrl = new URL(env.devOrigin || 'https://js.lclclerk.com');
const isSandbox = !!env.sandbox;
/** @type {() => import('@rspack/core').Configuration} */
const commonForDev = () => {
return {
module: {
rules: [svgLoader(), ...typescriptLoaderDev(), clerkUICSSLoader()],
},
plugins: [
new ReactRefreshPlugin(/** @type {any} **/ ({ overlay: { sockHost: devUrl.host } })),
isSandbox &&
new rspack.HtmlRspackPlugin({
minify: false,
template: './sandbox/template.html',
inject: false,
}),
].filter(Boolean),
devtool: 'eval-cheap-source-map',
output: {
publicPath: isSandbox ? `` : `${devUrl.origin}/npm`,
crossOriginLoading: 'anonymous',
filename: `[name].js`,
libraryTarget: 'umd',
},
optimization: {
minimize: false,
},
devServer: {
allowedHosts: ['all'],
headers: { 'Access-Control-Allow-Origin': '*' },
host: '0.0.0.0',
port: 4000,
hot: true,
liveReload: false,
client: { webSocketURL: `auto://${devUrl.host}/ws` },
...(isSandbox
? {
historyApiFallback: true,
}
: {}),
},
};
};
const entryToConfigMap = {
// prettier-ignore
[variants.clerk]: merge(
entryForVariant(variants.clerk),
common({ mode }),
commonForDev(),
),
// prettier-ignore
[variants.clerkBrowser]: merge(
entryForVariant(variants.clerkBrowser),
isSandbox ? { entry: { sandbox: './sandbox/app.ts' } } : {},
common({ mode }),
commonForDev(),
),
// prettier-ignore
[variants.clerkBrowserNoRHC]: merge(
entryForVariant(variants.clerkBrowserNoRHC),
common({ mode, disableRHC: true }),
commonForDev(),
),
[variants.clerkHeadless]: merge(
entryForVariant(variants.clerkHeadless),
common({ mode }),
commonForDev(),
// externalsForHeadless(),
),
[variants.clerkHeadlessBrowser]: merge(
entryForVariant(variants.clerkHeadlessBrowser),
common({ mode }),
commonForDev(),
// externalsForHeadless(),
),
};
if (!entryToConfigMap[variant]) {
throw new Error('Clerk variant does not exist in config');
}
return entryToConfigMap[variant];
};
module.exports = env => {
const mode = env.production ? 'production' : 'development';
const analysis = !!env.analysis;
return isProduction(mode) ? prodConfig({ mode, env, analysis }) : devConfig({ mode, env });
};