-
Notifications
You must be signed in to change notification settings - Fork 125
/
webpack.config.js
532 lines (482 loc) · 15.8 KB
/
webpack.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
/* eslint-disable no-console */
require('core-js/stable');
require('regenerator-runtime/runtime');
require('dotenv').config();
const fs = require('fs');
const fetch = require('node-fetch');
const path = require('path');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const WebpackBar = require('webpackbar');
const StylelintPlugin = require('stylelint-webpack-plugin');
const headerFooterData = require('../src/platform/landing-pages/header-footer-data.json');
const BUCKETS = require('../src/site/constants/buckets');
const ENVIRONMENTS = require('../src/site/constants/environments');
const scaffoldRegistry = require('../src/applications/registry.scaffold.json');
const facilitySidebar = require('../src/platform/landing-pages/facility-sidebar.json');
const { VAGOVSTAGING, VAGOVPROD, LOCALHOST } = ENVIRONMENTS;
const {
getAppManifests,
getWebpackEntryPoints,
} = require('./manifest-helpers');
// TODO: refactor the other approach for creating files without the hash so that we're only doing that in the webpack config: https://github.com/department-of-veterans-affairs/vets-website/blob/a012bad17e5bf024b0ea7326a72ae6a737e349ec/src/site/stages/build/plugins/process-entry-names.js#L35
const vaMedalliaStylesFilename = 'va-medallia-styles';
const generateWebpackDevConfig = require('./webpack.dev.config.js');
const getAbsolutePath = relativePath =>
path.join(__dirname, '../', relativePath);
const sharedModules = [
getAbsolutePath('src/platform/polyfills'),
'react',
'react-dom',
'react-redux',
'redux',
'redux-thunk',
'@sentry/browser',
];
const globalEntryFiles = {
polyfills: getAbsolutePath('src/platform/polyfills/preESModulesPolyfills.js'),
style: getAbsolutePath('src/platform/site-wide/sass/style.scss'),
[vaMedalliaStylesFilename]: getAbsolutePath(
'src/platform/site-wide/sass/va-medallia-style.scss',
),
styleConsolidated: getAbsolutePath(
'src/applications/proxy-rewrite/sass/style-consolidated.scss',
),
vendor: sharedModules,
// This is to solve the issue of the vendor file being cached
'shared-modules': sharedModules,
'web-components': getAbsolutePath('src/platform/site-wide/wc-loader.js'),
};
function getEntryManifests(entry) {
const allManifests = getAppManifests();
let entryManifests = allManifests;
if (entry) {
const entryNames = entry.split(',').map(name => name.trim());
entryManifests = allManifests.filter(manifest =>
entryNames.includes(manifest.entryName),
);
}
return entryManifests;
}
/**
* Get a list of all the entry points.
*
* @param {String} entry - List of comma-delimited entries to build. Builds all
* entries if no value is passed.
* @return {Object} - The entry file paths mapped to the entry names
*/
function getEntryPoints(entry) {
const manifestsToBuild = getEntryManifests(entry);
return getWebpackEntryPoints(manifestsToBuild);
}
/**
* Creates a mapping of scaffold asset filenames to file contents.
* Tries first to read from a local content-build by default and
* falls back to downloading from a remote content-build.
*
* @return {Object} - Map of scaffold asset filenames to file contents.
*/
async function getScaffoldAssets() {
const LOCAL_CONTENT_BUILD_ROOT = '../content-build';
const REMOTE_CONTENT_BUILD_ROOT =
'https://raw.githubusercontent.com/department-of-veterans-affairs/content-build/main';
const loadAsset = async contentBuildPath => {
const filename = path.basename(contentBuildPath);
const localPath = path.join(LOCAL_CONTENT_BUILD_ROOT, contentBuildPath);
if (fs.existsSync(localPath)) {
console.log(`Found local asset at ${localPath}.`);
return [filename, fs.readFileSync(localPath)];
}
const fileUrl = new URL(
path.join(REMOTE_CONTENT_BUILD_ROOT, contentBuildPath),
);
console.log(`Downloading asset from ${fileUrl.toString()}.`);
const response = await fetch(fileUrl);
if (!response.ok) {
throw new Error(
`Failed to fetch ${fileUrl}.\n\n${response.status}: ${
response.statusText
}`,
);
}
const fileContents = await response.text();
console.log(`Successfully downloaded ${filename}.`);
return [filename, fileContents];
};
const inlineScripts = ['record-event.js', 'static-page-widgets.js'].map(
filename => path.join('src/site/assets/js', filename),
);
const appRegistry = path.join('src/applications', 'registry.json');
const loadedAssets = await Promise.all(
[...inlineScripts, appRegistry].map(loadAsset),
);
return Object.fromEntries(loadedAssets);
}
/**
* Generates HTML files for each app and widget.
*
* @param {String} buildPath - Path to the overall build destination.
* @param {Object} scaffoldAssets - Map of scaffold asset filenames to file contents.
*
* @return {HtmlWebpackPlugin[]} - Array of HtmlWebpackPlugin instances,
* representing the HTML files to generate for each app and widget.
*/
function generateHtmlFiles(buildPath, scaffoldAssets) {
const appRegistry = JSON.parse(scaffoldAssets['registry.json']);
const loadInlineScript = filename => scaffoldAssets[filename];
// Modify the script and style tags output from HTML Webpack Plugin
// to match the order and attributes of tags from real content.
const modifyScriptAndStyleTags = originalTags => {
let scriptTags = [];
let styleTags = [];
originalTags.forEach(tag => {
if (tag.attributes.src?.match(/style/)) {
// Exclude style.entry.js, which gets included with the style chunk.
} else if (tag.attributes.src?.match(/polyfills/)) {
// Force polyfills.entry.js to be first since vendor.entry.js gets
// put first even with chunksSortMode: 'manual'. Also set nomodule
// so IE polyfills don't load in newer browsers
const tagWithNoModule = {
...tag,
attributes: { ...tag.attributes, nomodule: true },
};
scriptTags = [tagWithNoModule, ...scriptTags];
} else if (tag.attributes.href?.match(/style/)) {
// Put style.css before the app-specific stylesheet
styleTags = [tag, ...styleTags];
} else if (tag.attributes.src) {
scriptTags.push(tag);
} else if (tag.attributes.href) {
styleTags.push(tag);
} else {
throw new Error('Unexpected tag in <head>:', tag);
}
});
return [...styleTags, ...scriptTags].join('');
};
/* eslint-disable no-nested-ternary */
const generateHtmlFile = ({
appName,
entryName = 'static-pages',
rootUrl,
template = {},
widgetType,
widgetTemplate,
useLocalStylesAndComponents,
}) =>
new HtmlPlugin({
chunks: [
'polyfills',
useLocalStylesAndComponents ? null : 'web-components',
'vendor',
useLocalStylesAndComponents ? null : 'style',
entryName,
],
filename: path.join(buildPath, rootUrl, 'index.html'),
inject: false,
scriptLoading: 'defer',
template: 'src/platform/landing-pages/dev-template.ejs',
templateParameters: {
// Menu and navigation content
headerFooterData,
facilitySidebar,
// Helper functions
loadInlineScript,
modifyScriptAndStyleTags,
// Default template metadata.
breadcrumbs_override: [], // eslint-disable-line camelcase
includeBreadcrumbs: false,
loadingMessage: 'Please wait while we load the application for you.',
// App-specific config
entryName,
widgetType,
widgetTemplate,
rootUrl,
...template, // Unpack any template metadata from the registry entry.
},
title:
typeof template !== 'undefined' && template.title
? `${template.title} | Veterans Affairs`
: typeof appName !== 'undefined'
? appName
? `${appName} | Veterans Affairs`
: null
: 'VA.gov Home | Veterans Affairs',
});
/* eslint-enable no-nested-ternary */
return [...appRegistry, ...scaffoldRegistry]
.filter(({ rootUrl }) => rootUrl)
.map(generateHtmlFile);
}
module.exports = async (env = {}) => {
const { buildtype = LOCALHOST } = env;
const buildOptions = {
api: '',
buildtype,
host: LOCALHOST,
port: 3001,
scaffold: false,
watch: false,
destination: buildtype,
...env,
};
const apps = getEntryPoints(buildOptions.entry);
const entryFiles = { ...apps, ...globalEntryFiles };
const isOptimizedBuild = [VAGOVSTAGING, VAGOVPROD].includes(buildtype);
const scaffoldAssets = await getScaffoldAssets();
const appRegistry = JSON.parse(scaffoldAssets['registry.json']);
const envBucketUrl = BUCKETS[buildtype];
const sourceMapSlug = envBucketUrl || '';
const buildPath = path.resolve(
__dirname,
'../',
'build',
buildOptions.destination,
);
const baseConfig = {
mode: isOptimizedBuild ? 'production' : 'development',
devtool: false,
entry: entryFiles,
output: {
path: path.resolve(buildPath, 'generated'),
publicPath: '/generated/',
filename: '[name].entry.js',
chunkFilename: '[name].entry.js',
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
// Speed up compilation.
cacheDirectory: '.babelcache',
cacheCompression: false,
// Also see .babelrc
},
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'postcss-loader',
},
{
loader: 'sass-loader',
options: { sourceMap: true },
},
],
},
{
// if we want to minify these images, we could add img-loader
// but it currently only would apply to three images from uswds
test: /\.(jpe?g|png|gif)$/i,
use: {
loader: 'url-loader',
options: {
limit: 10000,
},
},
},
{
test: /\.svg/,
use: {
loader: 'svg-url-loader',
options: {
limit: 1024,
publicPath: './',
},
},
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: {
loader: 'url-loader',
options: {
limit: 7000,
mimetype: 'application/font-woff',
name: '[name].[ext]',
},
},
},
{
test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
},
{
test: /react-jsonschema-form\/lib\/components\/(widgets|fields\/ObjectField|fields\/ArrayField)/,
exclude: [/widgets\/index\.js/, /widgets\/TextareaWidget/],
use: {
loader: 'null-loader',
},
},
{ test: /\.afm$/, type: 'asset/source' },
// convert to base64 and include inline file system binary files used by fontkit and linebreak
{
enforce: 'post',
test: /fontkit[/\\]index.js$/,
loader: 'transform-loader',
options: {
brfs: {},
},
},
{
enforce: 'post',
test: /linebreak[/\\]src[/\\]linebreaker.js/,
loader: 'transform-loader',
options: {
brfs: {},
},
},
],
noParse: [/mapbox\/vendor\/promise.js$/],
},
resolve: {
alias: {
fs: 'pdfkit/js/virtual-fs.js',
'iconv-lite': false,
},
extensions: ['.js', '.jsx'],
fallback: {
fs: false,
assert: require.resolve('assert/'),
buffer: require.resolve('buffer/'),
crypto: false,
path: require.resolve('path-browserify'),
stream: require.resolve('readable-stream'),
util: require.resolve('util/'),
zlib: require.resolve('browserify-zlib'),
},
symlinks: false,
},
optimization: {
// 'chunkIds' and 'moduleIds' are set to 'named' for preserving
// consistency between full and single app builds
chunkIds: 'named',
moduleIds: 'named',
minimizer: [
new TerserPlugin({
terserOptions: {
output: {
beautify: false,
comments: false,
},
warnings: false,
},
parallel: true,
}),
],
splitChunks: {
cacheGroups: {
// this needs to be "vendors" to overwrite a default group
vendors: {
chunks: 'all',
test: 'vendor',
name: 'vendor',
enforce: true,
},
},
},
},
plugins: [
new webpack.DefinePlugin({
__BUILDTYPE__: JSON.stringify(buildtype),
__API__: JSON.stringify(buildOptions.api),
__REGISTRY__: JSON.stringify(appRegistry),
'process.env.MAPBOX_TOKEN': JSON.stringify(
process.env.MAPBOX_TOKEN || '',
),
'process.env.VIRTUAL_AGENT_BACKEND_URL': JSON.stringify(
process.env.VIRTUAL_AGENT_BACKEND_URL || '',
),
'process.env.USE_LOCAL_DIRECTLINE':
process.env.USE_LOCAL_DIRECTLINE || false,
}),
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
new webpack.SourceMapDevToolPlugin({
append: `\n//# sourceMappingURL=${sourceMapSlug}/generated/[url]`,
filename: '[file].map',
}),
new StylelintPlugin({
configFile: '.stylelintrc.json',
exclude: ['node_modules', 'build', 'coverage', '.cache'],
fix: true,
}),
new MiniCssExtractPlugin(),
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
new CopyPlugin({
patterns: [
{
from: 'src/site/assets',
to: buildPath,
},
{
from:
'node_modules/@department-of-veterans-affairs/component-library/dist/assets',
to: `${buildPath}/assets`,
},
],
}),
new WebpackBar(),
],
devServer: generateWebpackDevConfig(buildOptions),
};
if (!buildOptions.watch) {
baseConfig.plugins.push(
new WebpackManifestPlugin({
fileName: 'file-manifest.json',
filter: ({ isChunk }) => isChunk,
}),
);
}
// Optionally generate mocked HTML pages for apps without running content build.
if (buildOptions.scaffold) {
const scaffoldedHtml = generateHtmlFiles(buildPath, scaffoldAssets);
baseConfig.plugins.push(...scaffoldedHtml);
}
// Open homepage or specific app in browser
if (buildOptions.open) {
const target =
buildOptions.openTo || buildOptions.entry
? // Assumes the first in the list has a rootUrl
getEntryManifests(buildOptions.entry)[0].rootUrl
: '';
baseConfig.devServer.open = { target };
}
if (buildOptions.analyzer) {
baseConfig.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true,
}),
);
}
return baseConfig;
};