-
Notifications
You must be signed in to change notification settings - Fork 687
/
Copy pathgetClientConfig.js
286 lines (270 loc) · 10.1 KB
/
getClientConfig.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
/**
* @module Buildpack/WebpackTools
*/
const debug = require('debug')('pwa-buildpack:createClientConfig');
const path = require('path');
const webpack = require('webpack');
const WebpackAssetsManifest = require('webpack-assets-manifest');
const TerserPlugin = require('terser-webpack-plugin');
const getModuleRules = require('./getModuleRules');
const getResolveLoader = require('./getResolveLoader');
const RootComponentsPlugin = require('../plugins/RootComponentsPlugin');
const ServiceWorkerPlugin = require('../plugins/ServiceWorkerPlugin');
const UpwardIncludePlugin = require('../plugins/UpwardIncludePlugin');
const LocalizationPlugin = require('../plugins/LocalizationPlugin');
const VirtualModulesPlugin = require('webpack-virtual-modules');
function isDevServer() {
return process.argv.find(v => v.includes('webpack-dev-server'));
}
/**
* Create a Webpack configuration object for the browser bundle.
*
* @param {Buildpack/WebpackTools~WebpackConfigHelper} opts
* @returns {Object} A Webpack configuration for the main app.
*/
async function getClientConfig(opts) {
const {
mode,
context,
paths,
hasFlag,
vendor,
projectConfig,
stats,
resolver,
bus
} = opts;
let vendorTest = '[\\/]node_modules[\\/]';
if (vendor.length > 0) {
vendorTest += `(${vendor.join('|')})[\\\/]`;
}
debug('Creating client config');
// Create an instance of virtual modules enabling any plugin to create new virtual modules
const virtualModules = new VirtualModulesPlugin();
const config = {
mode,
context, // Node global for the running script's directory
stats,
entry: {
client: path.resolve(paths.src, 'index.js')
},
output: {
path: paths.output,
publicPath: '/',
filename:
mode === 'production' ? '[name].[contenthash].js' : '[name].js',
strictModuleExceptionHandling: true,
chunkFilename: '[name].[chunkhash].js'
},
module: {
rules: await getModuleRules(opts)
},
name: 'client-config',
resolve: resolver.config,
resolveLoader: getResolveLoader(),
plugins: [
new RootComponentsPlugin({
rootComponentsDirs: [
...hasFlag('rootComponents'),
context
].reduce(
(searchPaths, moduleDir) => [
...searchPaths,
path.join(moduleDir, 'RootComponents'),
path.join(moduleDir, 'src', 'RootComponents'),
path.join(moduleDir, 'lib', 'RootComponents')
],
[]
),
context
}),
new webpack.EnvironmentPlugin(projectConfig.env),
new UpwardIncludePlugin({
bus,
upwardDirs: [...hasFlag('upward'), context]
}),
new WebpackAssetsManifest({
output: 'asset-manifest.json',
entrypoints: true,
publicPath: '/',
// Add explicit properties to the asset manifest for
// upward.yml to use when evaluating app shell templates.
transform(assets) {
// All RootComponents go to prefetch, and all client scripts
// go to load.
assets.bundles = {
load: assets.entrypoints.client.js,
prefetch: []
};
Object.entries(assets).forEach(([name, value]) => {
if (name.match(/^RootCmp.*\.js$/)) {
const filenames = Array.isArray(value)
? value
: [value];
assets.bundles.prefetch.push(...filenames);
}
const ext = path.extname(name);
const type = ext && ext.replace(/^\./, '');
if (type) {
if (!assets[type]) {
assets[type] = {};
}
assets[type][path.basename(name, ext)] = value;
}
});
}
}),
new ServiceWorkerPlugin({
mode,
paths,
injectManifest: true,
enableServiceWorkerDebugging: !!projectConfig.section(
'devServer'
).serviceWorkerEnabled,
injectManifestConfig: {
include: [/\.(?:css|js|html|svg)$/],
swSrc: './src/ServiceWorker/sw.js',
swDest: './sw.js'
}
}),
new LocalizationPlugin({
virtualModules,
context,
dirs: [...hasFlag('i18n'), context] // Directories to search for i18n/*.json files
}),
virtualModules
],
devtool: 'source-map',
optimization: {
splitChunks: {
cacheGroups: {
/**
* Creating the vendors bundle. This bundle
* will have all the packages that the app
* needs to render. Since these dont change
* often, it is advantageous to bundle them
* separately and cache them on the client.
*/
vendor: {
test: new RegExp(vendorTest),
name: 'vendors',
chunks: 'all'
}
}
}
}
};
if (mode === 'development') {
debug('Modifying client config for development environment');
Object.assign(config.optimization, {
moduleIds: 'named',
nodeEnv: 'development',
minimize: false,
occurrenceOrder: true,
usedExports: true,
concatenateModules: true,
sideEffects: true
});
if (isDevServer()) {
// Using eval-source-map shows original source (non-transpiled) as
// well as comments.
// See https://webpack.js.org/configuration/devtool/
config.devtool = 'eval-source-map';
debug('Configuring Dev Server');
const PWADevServer = require('../PWADevServer');
await PWADevServer.configure(
{
graphqlPlayground: true,
...projectConfig.sections(
'devServer',
'imageOptimizing',
'imageService',
'customOrigin'
),
upwardPath: projectConfig.section('upwardJs').upwardPath
},
config
);
}
} else if (mode === 'production') {
const packageJson = require(path.resolve(context, './package.json'));
const packageRegex = /^@magento|^@apollo/;
const pwaStudioVersions = {
'pwa-studio': packageJson.version,
...Object.fromEntries(
Object.entries(packageJson.dependencies || {}).filter(
([packageKey]) => packageRegex.test(packageKey)
)
),
...Object.fromEntries(
Object.entries(packageJson.devDependencies || {}).filter(
([packageKey]) => packageRegex.test(packageKey)
)
)
};
try {
let buildId = projectConfig.section('staging').buildId;
buildId = buildId ? buildId.trim() : false;
if (buildId && buildId.length > 0) {
pwaStudioVersions['build-id'] = buildId;
}
} catch {
// Continue version banner
}
const versionBanner = Object.entries(pwaStudioVersions)
.sort(([packageKeyOne], [packageKeyTwo]) => {
return -1 * packageKeyOne.localeCompare(packageKeyTwo);
})
.map(([packageKey, version]) => `${packageKey}: ${version}`)
.join(', ');
debug('Modifying client config for production environment');
config.performance = {
hints: 'warning'
};
config.devtool = false;
config.optimization = {
...config.optimization,
moduleIds: 'hashed',
/**
* This will move the runtime configuration to
* its own bundle. Since runtime config tends to
* change on each compile even though the app logic
* doesn't, if not separated the whole client bundle
* needs to be downloaded. Separating them will only
* download runtime bundle and use the cached client code.
*/
runtimeChunk: 'single',
minimizer: [
new TerserPlugin({
parallel: true,
cache: true,
terserOptions: {
ecma: 8,
parse: {
ecma: 8
},
compress: {
drop_console: false
},
output: {
ecma: 7,
semicolons: false
},
keep_fnames: true
}
}),
new webpack.BannerPlugin({
banner: `@version ${versionBanner}`
})
]
};
} else {
debug(
`Unable to verify environment. Cancelling client config creation. Received mode: ${mode}`
);
throw Error(`Unsupported environment mode in webpack config: ${mode}`);
}
debug('Client config created');
return config;
}
module.exports = getClientConfig;