-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathconfig.js
More file actions
514 lines (472 loc) · 17.8 KB
/
config.js
File metadata and controls
514 lines (472 loc) · 17.8 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
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
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-env node */
// For more information on these settings, see https://webpack.js.org/configuration
import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer'
import {resolve} from 'path'
import fse from 'fs-extra'
import webpack from 'webpack'
// Third-Party Plugins
import CopyPlugin from 'copy-webpack-plugin'
import LoadablePlugin from '@loadable/webpack-plugin'
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'
import SpeedMeasurePlugin from 'speed-measure-webpack-plugin'
import WebpackNotifierPlugin from 'webpack-notifier'
// Local Plugins
import {sdkReplacementPlugin} from './plugins'
// Constants
import {CLIENT, SERVER, CLIENT_OPTIONAL, SSR, REQUEST_PROCESSOR} from './config-names'
const projectDir = process.cwd()
const pkg = fse.readJsonSync(resolve(projectDir, 'package.json'))
const buildDir = process.env.PWA_KIT_BUILD_DIR
? resolve(process.env.PWA_KIT_BUILD_DIR)
: resolve(projectDir, 'build')
const production = 'production'
const development = 'development'
const analyzeBundle = process.env.MOBIFY_ANALYZE === 'true'
const mode = process.env.NODE_ENV === production ? production : development
const INSPECT = process.execArgv.some((arg) => /^--inspect(?:-brk)?(?:$|=)/.test(arg))
const DEBUG = mode !== production && process.env.DEBUG === 'true'
const CI = process.env.CI
const disableHMR = process.env.HMR === 'false'
if ([production, development].indexOf(mode) < 0) {
throw new Error(`Invalid mode "${mode}"`)
}
export const SUPPORTED_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.json']
// TODO: can these be handled in package.json as peerDependencies?
// https://salesforce-internal.slack.com/archives/C0DKK1FJS/p1672939909212589
// due to to how the sdks work and the potential of these npm deps coming
// from multiple places, we need to force them to one place where they're found
export const DEPS_TO_DEDUPE = [
'babel-runtime',
'@tanstack/react-query',
'@loadable/component',
'@loadable/server',
'@loadable/webpack-plugin',
'svg-sprite-loader',
'react',
'react-router-dom',
'react-dom',
'react-helmet',
'webpack-hot-middleware',
'react-intl',
'@chakra-ui/icons',
'@chakra-ui/react',
'@chakra-ui/skip-nav',
'@emotion/react'
]
const getBundleAnalyzerPlugin = (name = 'report', pluginOptions) =>
new BundleAnalyzerPlugin({
analyzerMode: 'static',
defaultSizes: 'gzip',
openAnalyzer: CI !== 'true',
generateStatsFile: true,
reportFilename: `${name}.html`,
reportTitle: `${name} bundle analysis result`,
statsFilename: `${name}-analyzer-stats.json`,
...pluginOptions
})
const entryPointExists = (segments) => {
for (let ext of SUPPORTED_FILE_EXTENSIONS) {
const p = resolve(projectDir, ...segments) + ext
if (fse.existsSync(p)) {
return true
}
}
return false
}
const getAppEntryPoint = () => './src/main'
const getServerEntryPoint = () => './src/ssr.js'
const getPublicPathEntryPoint = () => {
return resolve(
projectDir,
'node_modules',
'@salesforce',
'pwa-kit-dev',
'ssr',
'server',
'public-path'
)
}
const findDepInStack = (pkg) => {
// Look for the SDK node_modules in two places because in CI,
// pwa-kit-dev is published under a 'dist' directory, which
// changes this file's location relative to the package root.
const candidates = [
resolve(projectDir, 'node_modules', pkg),
resolve(__dirname, '..', '..', 'node_modules', pkg),
resolve(__dirname, '..', '..', '..', 'node_modules', pkg)
]
let candidate
for (candidate of candidates) {
if (fse.existsSync(candidate)) {
return candidate
}
}
return candidate
}
const baseConfig = (target) => {
if (!['web', 'node'].includes(target)) {
throw Error(`The value "${target}" is not a supported webpack target`)
}
class Builder {
constructor() {
this.config = {
watchOptions: {
aggregateTimeout: 1000
},
target,
mode,
...(target === 'node'
? {
ignoreWarnings: [
// These can be ignored fairly safely for node targets, where
// bundle size is not super critical. Express generates this warning,
// because it uses dynamic require() calls, which cause Webpack to
// bundle the whole library.
/Critical dependency: the request of a dependency is an expression/
]
}
: {}),
infrastructureLogging: {
level: 'error'
},
stats: {
all: false,
modules: false,
errors: true,
warnings: true,
moduleTrace: true,
errorDetails: true,
colors: true,
assets: false,
excludeAssets: [/.*img\/.*/, /.*svg\/.*/, /.*json\/.*/, /.*static\/.*/]
},
optimization: {
minimize: mode === production
},
output: {
publicPath: '',
path: buildDir
},
resolve: {
extensions: SUPPORTED_FILE_EXTENSIONS,
alias: {
...Object.assign(
...DEPS_TO_DEDUPE.map((dep) => ({
[dep]: findDepInStack(dep)
}))
)
},
...(target === 'web' ? {fallback: {crypto: false}} : {})
},
// To add a new config for an extension, you can add a new element to the plugins array with the key and value as follows:
// The key should be the name of the plugin, and the value should be a boolean.
// The value should be true if the plugin is enabled, and false if it is disabled.
// The key should start with SFDC_EXT_, so that it's clear that it is an extension and not part of the core PWA Kit.
// For example, to add a new config for the Hello World extension, you can add the following:
// new webpack.DefinePlugin({
// SFDC_EXT_HELLO_WORLD_ENABLED: true
// })
plugins: [
new webpack.DefinePlugin({
DEBUG,
NODE_ENV: `'${process.env.NODE_ENV}'`,
WEBPACK_TARGET: `'${target}'`,
['global.GENTLY']: false
}),
mode === development && new webpack.NoEmitOnErrorsPlugin(),
sdkReplacementPlugin(),
// Don't chunk if it's a node target – faster Lambda startup.
target === 'node' && new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1})
].filter(Boolean),
module: {
rules: [
ruleForBabelLoader(),
target === 'node' && {
test: /\.svg$/,
loader: findDepInStack('svg-sprite-loader')
},
target === 'web' && {
test: /\.svg$/,
loader: findDepInStack('ignore-loader')
},
{
test: /\.html$/,
exclude: /node_modules/,
use: {
loader: findDepInStack('html-loader')
}
},
{
test: /\.js$/,
enforce: 'pre',
use: {
loader: findDepInStack('source-map-loader')
}
}
].filter(Boolean)
}
}
}
extend(callback) {
this.config = callback(this.config)
return this
}
build() {
// Clean up temporary properties, to be compatible with the config schema
this.config.module.rules.filter((rule) => rule.id).forEach((rule) => delete rule.id)
return this.config
}
}
return new Builder()
}
const withChunking = (config) => {
return {
...config,
output: {
...config.output,
filename: '[name].js',
chunkFilename: '[name].js' // Support chunking with @loadable/components
},
optimization: {
minimize: mode === production,
splitChunks: {
cacheGroups: {
vendor: {
test: /(node_modules)|(packages\/.*\/dist)/,
name: 'vendor',
chunks: 'all'
}
}
}
}
}
}
const staticFolderCopyPlugin = new CopyPlugin({
patterns: [
{
from: 'static',
to: 'static/',
noErrorOnMissing: true
}
]
})
const ruleForBabelLoader = (babelPlugins) => {
return {
id: 'babel-loader',
test: /(\.js(x?)|\.ts(x?))$/,
exclude: /node_modules/,
use: [
{
loader: findDepInStack('thread-loader'),
options: {
// eslint-disable-next-line @typescript-eslint/no-var-requires
workers: Math.min(4, require('os').cpus().length),
workerParallelJobs: 100
}
},
{
loader: findDepInStack('babel-loader'),
options: {
rootMode: 'upward',
cacheDirectory: true,
...(babelPlugins ? {plugins: babelPlugins} : {})
}
}
]
}
}
const findAndReplace = (array = [], findFn = () => {}, replacement) => {
const clone = array.slice(0)
const index = clone.findIndex(findFn)
if (index === -1) {
return array
}
clone.splice(index, 1, replacement)
return clone
}
const enableReactRefresh = (config) => {
if (mode !== development || disableHMR) {
return config
}
const newRule = ruleForBabelLoader([require.resolve('react-refresh/babel')])
const rules = findAndReplace(config.module.rules, (rule) => rule.id === 'babel-loader', newRule)
// NOTE: This ensures that files processed with the override-loader do not get processed again for hmr.
rules[0].exclude = (resource) => resource.includes('?noHMR=true')
return {
...config,
module: {
...config.module,
rules
},
entry: {
...config.entry,
main: [
'webpack-hot-middleware/client?path=/__mrt/hmr',
getPublicPathEntryPoint(),
getAppEntryPoint()
]
},
plugins: [
...config.plugins,
new webpack.HotModuleReplacementPlugin(),
new ReactRefreshWebpackPlugin({
overlay: false
})
]
}
}
const client =
entryPointExists(['src', 'main']) &&
baseConfig('web')
.extend(withChunking)
.extend((config) => {
return {
...config,
// Must be named "client". See - https://www.npmjs.com/package/webpack-hot-server-middleware#usage
name: CLIENT,
// use source map to make debugging easier
devtool:
mode === development || process.env.PWA_KIT_SOURCE_MAP === 'true'
? 'source-map'
: false,
entry: {
main: getAppEntryPoint()
},
plugins: [
...config.plugins,
new LoadablePlugin({writeToDisk: true}),
analyzeBundle && getBundleAnalyzerPlugin(CLIENT)
].filter(Boolean),
// Hide the performance hints, since we already have a similar `bundlesize` check in `template-chakra-storefront` package
performance: {
hints: false
}
}
})
.extend(enableReactRefresh)
.build()
const optional = (name, path) => {
return fse.existsSync(path) ? {[name]: path} : {}
}
const clientOptional = baseConfig('web')
.extend((config) => {
return {
...config,
name: CLIENT_OPTIONAL,
entry: {
...optional('loader', resolve(projectDir, 'src', 'loader.js')),
...optional('worker', resolve(projectDir, 'worker', 'main.js')),
...optional('fetch-polyfill', resolve(projectDir, 'node_modules', 'whatwg-fetch'))
},
// use source map to make debugging easier
devtool:
mode === development || process.env.PWA_KIT_SOURCE_MAP === 'true'
? 'source-map'
: false,
plugins: [
...config.plugins,
analyzeBundle && getBundleAnalyzerPlugin(CLIENT_OPTIONAL)
].filter(Boolean)
}
})
.build()
const renderer =
fse.existsSync(resolve(projectDir, 'node_modules', '@salesforce', 'pwa-kit-react-sdk')) &&
baseConfig('node')
.extend((config) => {
return {
...config,
// Must be named "server". See - https://www.npmjs.com/package/webpack-hot-server-middleware#usage
name: SERVER,
entry: '@salesforce/pwa-kit-react-sdk/ssr/server/react-rendering.js',
// use eval-source-map for server-side debugging
devtool:
(mode === development && INSPECT) || process.env.PWA_KIT_SOURCE_MAP === 'true'
? 'eval-source-map'
: false,
output: {
path: buildDir,
// We want to split the build on local development to reduce memory usage.
// It is required to have a single entry point for the remote server.
// See pwa-kit-runtime/ssr/server/build-remote-server.js render method.
filename: mode === development ? '[name]-server.js' : 'server-renderer.js',
libraryTarget: 'commonjs2'
},
plugins: [
...config.plugins,
staticFolderCopyPlugin,
// Keep this on the slowest-to-build item - the server-side bundle.
new WebpackNotifierPlugin({
title: `PWA Kit Project: ${pkg.name}`,
excludeWarnings: true,
skipFirstNotification: true
}),
analyzeBundle && getBundleAnalyzerPlugin('server-renderer')
].filter(Boolean)
}
})
.build()
const ssr = (() => {
// Only compile the ssr file when we're building for prod.
if (mode === production) {
return baseConfig('node')
.extend((config) => {
return {
...config,
...(process.env.PWA_KIT_SOURCE_MAP === 'true' ? {devtool: 'source-map'} : {}),
// Must *not* be named "server". See - https://www.npmjs.com/package/webpack-hot-server-middleware#usage
name: SSR,
entry: getServerEntryPoint(),
output: {
path: buildDir,
filename: 'ssr.js',
libraryTarget: 'commonjs2'
},
plugins: [
...config.plugins,
staticFolderCopyPlugin,
analyzeBundle && getBundleAnalyzerPlugin(SSR)
].filter(Boolean)
}
})
.build()
} else {
return undefined
}
})()
const requestProcessor =
entryPointExists(['src', 'request-processor']) &&
baseConfig('node')
.extend((config) => {
return {
...config,
name: REQUEST_PROCESSOR,
entry: './src/request-processor.js',
output: {
path: buildDir,
filename: 'request-processor.js',
libraryTarget: 'commonjs2'
},
// use eval-source-map for server-side debugging
devtool:
(mode === development && INSPECT) || process.env.PWA_KIT_SOURCE_MAP === 'true'
? 'eval-source-map'
: false,
plugins: [
...config.plugins,
analyzeBundle && getBundleAnalyzerPlugin(REQUEST_PROCESSOR)
].filter(Boolean)
}
})
.build()
module.exports = [client, ssr, renderer, clientOptional, requestProcessor]
.filter(Boolean)
.map((config) => {
return new SpeedMeasurePlugin({disable: !process.env.MEASURE}).wrap(config)
})