@xh/hoist-dev-utils 6.0.0-SNAPSHOT.1632860348588

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,754 @@
1
+ /*
2
+ * This file belongs to Hoist, an application development toolkit
3
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
+ *
5
+ * Copyright © 2021 Extremely Heavy Industries Inc.
6
+ */
7
+ 'use strict';
8
+
9
+ const _ = require('lodash'),
10
+ path = require('path'),
11
+ fs = require('fs'),
12
+ webpack = require('webpack'),
13
+ BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin,
14
+ CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'),
15
+ {CleanWebpackPlugin} = require('clean-webpack-plugin'),
16
+ CopyWebpackPlugin = require('copy-webpack-plugin'),
17
+ MiniCssExtractPlugin = require('mini-css-extract-plugin'),
18
+ FaviconsWebpackPlugin = require('favicons-webpack-plugin'),
19
+ HtmlWebpackPlugin = require('html-webpack-plugin'),
20
+ HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin'),
21
+ TerserPlugin = require('terser-webpack-plugin'),
22
+ WebpackBar = require('webpackbar'),
23
+ DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin'),
24
+ parseChangelogMarkdown = require('changelog-parser'),
25
+ babelCorePkg = require('@babel/core/package'),
26
+ devUtilsPkg = require('./package'),
27
+ basePath = fs.realpathSync(process.cwd());
28
+
29
+ // These are not direct deps of hoist-dev-utils, so might be undefined - e.g. when running
30
+ // this script locally to debug via `yarn link`.
31
+ let hoistReactPkg, reactPkg;
32
+ try {hoistReactPkg = require('@xh/hoist/package')} catch (e) {hoistReactPkg = {version: 'NOT_FOUND'}}
33
+ try {reactPkg = require('react/package')} catch (e) {reactPkg = {version: 'NOT_FOUND'}}
34
+
35
+ /**
36
+ * Consolidated Webpack configuration for both dev-time and production builds of Hoist React web applications.
37
+ *
38
+ * Sample commands to run configurations produced by this method include:
39
+ * `webpack --env.prodBuild --env.appVersion=1.2.3` to trigger a build at version 1.2.3
40
+ * `webpack-dev-server --env.inlineHoist` to run webpack dev server w/hoist-react in inline mode
41
+ *
42
+ * @param {Object} env - config passed in from app webpack config or the CLI via --env flags.
43
+ * @param {string} env.appCode - short, internal code for the application - baked into client as
44
+ * XH.appCode. Should be lowercase, dash-separated, and should match the Gradle project name
45
+ * (e.g. portfolio-manager).
46
+ * @param {string} [env.appName] - user-facing display name for the application - baked into client
47
+ * as XH.appName. Should be title cased and space-separated. If null, will be defaulted based
48
+ * on appCode (e.g. portfolio-manager -> Portfolio Manager).
49
+ * @param {string} [env.appVersion] - client version - baked into client as XH.appVersion
50
+ * @param {string} [env.appBuild] - build/git tag - baked into client as XH.appBuild
51
+ * @param {boolean} [env.prodBuild=false] - true to indicate this is a build (as opposed to run of
52
+ * webpack-dev-server)
53
+ * @param {boolean} [env.inlineHoist=false] - true to use a locally checked-out copy of hoist-react
54
+ * when running the dev server, as opposed to using the downloaded dependency. This allows
55
+ * hoist-react developers to test plugin changes. Dev-mode only.
56
+ * @param {boolean} [env.inlineHoistOpenFin=false] - true to use a locally checked-out copy of the
57
+ * hoist-openfin plugin - as with `inlineHoist` above. Dev-mode only.
58
+ * @param {string} env.agGridLicenseKey - key for ag-Grid enterprise license purchased / supplied
59
+ * for this application and your organization. Applicable only to Hoist React v34 and prior -
60
+ * as of v35 license key management is now handled exclusively within the application codebase.
61
+ * @param {Object} [env.resolveAliases] - object mapping for custom webpack module resolution.
62
+ * When inlineHoist=true, a mapping between @xh/hoist and the local path will be added.
63
+ * @param {boolean} [env.analyzeBundles=false] - true to launch an interactive bundle analyzer to
64
+ * review output bundles, contents, and sizes.
65
+ * @param {boolean} [env.checkForDupePackages=true] - true (default) to run build through
66
+ * DuplicatePackageCheckerPlugin and output a build-time console warning if duplicate packages
67
+ * have been resolved due to non-overlapping dependencies. Set to false to disable if dupe
68
+ * warnings are not desired / distracting.
69
+ * @param {string[]} [env.dupePackageCheckExcludes] - optional list of string package names to
70
+ * exclude from dupe package checking. Defaults to ['tslib'].
71
+ * @param {string} [env.baseUrl] - root path prepended to all relative URLs called via FetchService
72
+ * (the core Hoist service for making Ajax requests). Defaults to `/api/` in production mode to
73
+ * work with proxy-based deployments and to `$devHost:$devGrailsPort` in dev mode.
74
+ * This should not typically need to be changed at the app level.
75
+ * @param {string[]} [env.babelIncludePaths] - additional paths to pass Babel for transpiling via
76
+ * settings shared with app-level and @xh/hoist code. Intended for custom packages.
77
+ * @param {string[]} [env.babelExcludePaths] - paths to exclude from Babel transpilation. An example
78
+ * use would be a local package with a nested node_modules folder.
79
+ * @param {string} [env.contextRoot] - root path for where the app will be served, used as the base
80
+ * path for static files.
81
+ * @param {boolean} [env.copyPublicAssets] - true (default) to copy the /client-app/public directory
82
+ * and its contents into the root of the build. Note that files within this directory will not
83
+ * be otherwise processed, named with a hash, etc. Use for static assets you wish to link to
84
+ * without using an import to run through the url or file-loader.
85
+ * @param {boolean} [env.parseChangelog] - true (default) to parse a `CHANGELOG.md` file in the
86
+ * project root directory into JSON and make available for import by `XH.changelogService`.
87
+ * @param {string} [env.favicon] - relative path to a favicon source image to be processed.
88
+ * @param {Object} [env.faviconManifestConfig] - override values for config passed to favicons-
89
+ * webpack-plugin, which not only generates favicon variations but ALSO creates and injects a
90
+ * manifest.json file into the HTML source. This controls certain options related to adding a
91
+ * mobile app to a device home screen, as well as "installing" an app via Chrome's "create
92
+ * shortcut" option. See https://github.com/itgalaxy/favicons#usage for options. Note `favicon`
93
+ * must also specified for these options to have any effect.
94
+ * @param {string} [env.stats] - stats output - see https://webpack.js.org/configuration/stats/.
95
+ * @param {string} [env.devHost] - hostname for both local Grails and Webpack dev servers.
96
+ * Defaults to localhost, but may be overridden to a proper hostname for testing on alternate
97
+ * workstations or devices. Will be automatically set to lowercase to comply with
98
+ * webpack-dev-server's host checking. Dev-mode only.
99
+ * @param {number} [env.devGrailsPort] - port of local Grails server. Dev-mode only.
100
+ * @param {number} [env.devWebpackPort] - port on which to start webpack-dev server. Dev-mode only.
101
+ * @param {string} [env.devServerOpenPage] - path to auto-open when webpack-dev-server starts.
102
+ * Leave null to disable automatic page open on startup.
103
+ * @param {string[]} [env.targetBrowsers] - array of browserslist queries specifying target browsers
104
+ * for Babel and CSS transpilation and processing.
105
+ * @param {Object} [env.babelPresetEnvOptions] - options to spread onto / override defaults passed
106
+ * here to the Babel loader preset-env preset config.
107
+ * @param {Object} [env.terserOptions] - options to spread onto / override defaults passed here to
108
+ * the Terser minification plugin for production builds.
109
+ * @param {(boolean|string)} [env.sourceMaps] - control sourceMap generation. Set to `true`
110
+ * (default) to enable defaults specific to dev vs. prod builds, `false` to disable source
111
+ * maps entirely, special string `'devOnly'` to enable default for dev and disable in prod, or
112
+ * any other valid Webpack `devtool` string to specify a mode directly.
113
+ * @param {boolean} [env.loadAllBlueprintJsIcons] - false (default) to only load the BlueprintJs
114
+ * icons required by Hoist React components, resulting in a much smaller bundle size. Set to
115
+ * true if your app wishes to access all the BP icons (but consider FontAwesome instead!).
116
+ * @param {(Object|boolean)} [env.devHttps] - Object of the form `{ca, cert, key}`, with each
117
+ * key pointing to the required resource for a full SSL config. Pass `true` to serve locally
118
+ * over SSL w/o providing a cert (browser will warn). Applies to local dev only, no effect on
119
+ * production builds.
120
+ */
121
+ async function configureWebpack(env) {
122
+ if (!env.appCode) throw 'Missing required "appCode" config - cannot proceed';
123
+
124
+ const appCode = env.appCode,
125
+ appName = env.appName || _.startCase(appCode),
126
+ appVersion = env.appVersion || '1.0-SNAPSHOT',
127
+ appBuild = env.appBuild || 'UNKNOWN',
128
+ prodBuild = env.prodBuild === true,
129
+ inlineHoist = !prodBuild && env.inlineHoist === true,
130
+ inlineHoistOpenFin = !prodBuild && env.inlineHoistOpenFin === true,
131
+ resolveAliases = Object.assign({}, env.resolveAliases),
132
+ analyzeBundles = env.analyzeBundles === true,
133
+ checkForDupePackages = env.checkForDupePackages !== false,
134
+ dupePackageCheckExcludes = env.dupePackageCheckExcludes || ['tslib'],
135
+ devHost = (env.devHost ? env.devHost.toLowerCase() : 'localhost'),
136
+ devHttps = prodBuild ?
137
+ null :
138
+ _.isPlainObject(env.devHttps) ?
139
+ {
140
+ ca: fs.readFileSync(env.devHttps.ca),
141
+ cert: fs.readFileSync(env.devHttps.cert),
142
+ key: fs.readFileSync(env.devHttps.key)
143
+ } : !!env.devHttps,
144
+ devGrailsPort = env.devGrailsPort || 8080,
145
+ devWebpackPort = env.devWebpackPort || 3000,
146
+ baseUrl = env.baseUrl || (prodBuild ? '/api/' : `http://${devHost}:${devGrailsPort}/`),
147
+ babelIncludePaths = env.babelIncludePaths || [],
148
+ babelExcludePaths = env.babelExcludePaths || [],
149
+ contextRoot = env.contextRoot || '/',
150
+ copyPublicAssets = env.copyPublicAssets !== false,
151
+ parseChangelog = env.parseChangelog !== false,
152
+ favicon = env.favicon || null,
153
+ faviconManifestConfig = env.faviconManifestConfig || {},
154
+ stats = env.stats || 'errors-only',
155
+ targetBrowsers = env.targetBrowsers || [
156
+ 'last 2 Chrome versions',
157
+ 'last 2 Safari versions',
158
+ 'last 2 iOS versions',
159
+ 'last 2 Edge versions'
160
+ ],
161
+ babelPresetEnvOptions = env.babelPresetEnvOptions || {},
162
+ terserOptions = env.terserOptions || {},
163
+ sourceMaps = env.sourceMaps === undefined ? true : env.sourceMaps,
164
+ buildDate = new Date();
165
+
166
+ process.env.BABEL_ENV = prodBuild ? 'production' : 'development';
167
+ process.env.NODE_ENV = prodBuild ? 'production' : 'development';
168
+
169
+ logSep();
170
+ logMsg(`Building ${appName} v${appVersion}`);
171
+ if (appBuild !== 'UNKNOWN') logMsg(` Build ${appBuild}`);
172
+ logMsg(` ${buildDate.toISOString()}`);
173
+ logSep();
174
+ if (prodBuild) logMsg('🚀 Production build enabled');
175
+ if (!prodBuild) logMsg('💻 Development mode enabled');
176
+ if (inlineHoist) logMsg('🏗️ Inline Hoist enabled');
177
+ if (inlineHoistOpenFin) logMsg('🏗️ Inline Hoist-OpenFin enabled');
178
+ if (analyzeBundles) logMsg('🎁 Bundle analysis enabled');
179
+ logSep();
180
+ logMsg('📚 Key libraries:');
181
+ logMsg(` > @xh/hoist ${inlineHoist ? 'INLINE' : 'v' + hoistReactPkg.version}`);
182
+ logMsg(` > @xh/hoist-dev-utils v${devUtilsPkg.version}`);
183
+ logMsg(` > @babel/core v${babelCorePkg.version}`);
184
+ logMsg(` > react v${reactPkg.version}`);
185
+ logMsg(` > webpack v${webpack.version}`);
186
+ logMsg(` > node ${process.version}`);
187
+ logSep();
188
+ logMsg('🎯 Targets:');
189
+ targetBrowsers.forEach(it => logMsg(` > ${it}`));
190
+ logSep();
191
+
192
+ const srcPath = path.resolve(basePath, 'src'),
193
+ outPath = path.resolve(basePath, 'build'),
194
+ publicPath = contextRoot; // Path on which fully built app is served - i.e. root context
195
+
196
+ // Resolve Hoist as either a sibling (inline, checked-out) project or a downloaded package dependency
197
+ const hoistPath = inlineHoist ?
198
+ path.resolve(basePath, '../../hoist-react') :
199
+ path.resolve(basePath, 'node_modules/@xh/hoist');
200
+
201
+ // Resolve Hoist-based path to replacement Blueprint icons (if available, requires HR >= v35.2.
202
+ const bpIconStubsPath = path.resolve(hoistPath, 'static/requiredBlueprintIcons.js'),
203
+ bpIconStubsExist = fs.existsSync(bpIconStubsPath),
204
+ loadAllBlueprintJsIcons = env.loadAllBlueprintJsIcons === true || !bpIconStubsExist;
205
+
206
+ // Resolve path to script for preflight checks. With HR >= v36.1 this routine has been broken
207
+ // out into a standalone JS file to avoid the use of inline script tags. Script will be left
208
+ // unprocessed/unbundled and injected into HTML index files prior to any bundles.
209
+ const preflightScriptPath = path.resolve(hoistPath, 'static/preflight.js'),
210
+ preflightScriptExists = fs.existsSync(preflightScriptPath);
211
+
212
+ // Tell webpack where to look for modules when resolving imports - this is the key to getting
213
+ // inlineHoist mode to look in within the checked-out hoist-react project at hoistPath.
214
+ if (inlineHoist) {
215
+ resolveAliases['@xh/hoist'] = hoistPath;
216
+
217
+ // This ensures that we use the same instance of react in hoist-react as in the app - needed
218
+ // to get hooks working since they will throw an error if the react instance that the hook
219
+ // was imported from is different than the instance that was used to render the component
220
+ // (which will always be the instance hoist-react has when using element factories)
221
+ resolveAliases.react = path.resolve('./node_modules/react');
222
+ }
223
+
224
+ // When running inline, resolve inline Hoist's own node_modules package so we can tell Babel to exclude
225
+ const hoistNodeModulesPath = inlineHoist ?
226
+ path.resolve(hoistPath, 'node_modules') :
227
+ null;
228
+
229
+ // Also get a handle on the nested @xh/hoist-dev-utils/node_modules path - dev-utils dependencies
230
+ // (namely loaders) can be installed here due to the vagaries of node module version / conflict resolution.
231
+ const devUtilsNodeModulesPath = path.resolve(basePath, 'node_modules/@xh/hoist-dev-utils/node_modules');
232
+
233
+ // Determine source map (devtool) mode.
234
+ let devtool;
235
+ if (!sourceMaps) {
236
+ devtool = false;
237
+ } else if (sourceMaps === true) {
238
+ devtool = prodBuild ? 'source-map' : 'eval-source-map';
239
+ } else if (sourceMaps === 'devOnly') {
240
+ devtool = prodBuild ? false : 'eval-source-map';
241
+ } else {
242
+ devtool = sourceMaps;
243
+ }
244
+
245
+ // Parse CHANGELOG.md and write to tmp .json file, if requested. Write fallback file if disabled
246
+ // or parsing fails, then install a resolver alias to support import from XH.changelogService.
247
+ const tmpPath = path.resolve(basePath, 'node_modules', '.xhtmp'),
248
+ clDestPath = path.resolve(tmpPath, 'changelog.json');
249
+ if (!fs.existsSync(tmpPath)) fs.mkdirSync(tmpPath);
250
+ let clDestUpdated = false;
251
+ if (parseChangelog) {
252
+ logMsg('📜 Changelog:');
253
+ const clSrcPath = path.resolve(basePath, '..', 'CHANGELOG.md');
254
+ if (!fs.existsSync(clSrcPath)) {
255
+ logMsg(' > CHANGELOG.md not found');
256
+ } else {
257
+ try {
258
+ const clJson = await parseChangelogMarkdown(clSrcPath),
259
+ versions = clJson.versions,
260
+ latestVer = versions.length > 0 ? versions[0].version : null;
261
+ fs.writeFileSync(clDestPath, JSON.stringify(clJson));
262
+ clDestUpdated = true;
263
+ logMsg(` > Parsed: ${versions.length} versions`);
264
+ logMsg(` > Latest: ${latestVer || '???'}`);
265
+ } catch (e) {
266
+ logMsg(` > ERROR - exception parsing CHANGELOG.md: ${e}`);
267
+ }
268
+ }
269
+ logSep();
270
+ }
271
+ // Write dummy file if CL disabled or has failed to parse/write changelog.json.
272
+ // Ensures we always have a file with either updated or appropriately empty JSON to alias.
273
+ if (!clDestUpdated) fs.writeFileSync(clDestPath, '{}');
274
+ // Setup resolver alias to synthetic import path used by XH.changelogService.
275
+ resolveAliases['@xh/app-changelog.json'] = clDestPath;
276
+
277
+ // Resolve app entry points - one for each file within src/apps/ - to create bundle entries below.
278
+ const appDirPath = path.resolve(srcPath, 'apps'),
279
+ apps = fs
280
+ .readdirSync(appDirPath)
281
+ .filter(f => f.endsWith('.js'))
282
+ .map(f => {
283
+ return {
284
+ name: f.replace('.js', ''),
285
+ path: path.resolve(appDirPath, f)
286
+ };
287
+ }),
288
+ appNames = apps.map(it => it.name);
289
+
290
+ // Build Webpack entry config, with keys for each JS app to be bundled.
291
+ const appEntryPoints = {};
292
+ apps.forEach(app => {
293
+ // Ensure core-js and regenerator-runtime both imported for every app bundle - they are
294
+ // specified as dependencies by Hoist and imported once in its polyfills.js file.
295
+ appEntryPoints[app.name] = [
296
+ path.resolve(hoistPath, 'static/polyfills.js'),
297
+ app.path
298
+ ];
299
+ });
300
+
301
+ logMsg('🎁 App bundle entry points:');
302
+ appNames.forEach(it => logMsg(` > ${it}`));
303
+ logSep();
304
+ logMsg('🤕 Something going wrong?');
305
+ logMsg(' > support@xh.io');
306
+ logMsg(' > https://xh.io/contact/');
307
+ logSep();
308
+
309
+ return {
310
+ mode: prodBuild ? 'none' : 'development',
311
+
312
+ // One named entry chunk per app, as above.
313
+ entry: appEntryPoints,
314
+
315
+ output: {
316
+ // Output built assets in directories per entry point / chunk.
317
+ // Use chunkhash in prod to get distinct hashes for app vs. common chunks (throws error in dev - investigate)
318
+ filename: prodBuild ? '[name]/[name].[chunkhash:8].js' : '[name]/[name].[hash:8].js',
319
+ path: outPath,
320
+ publicPath: publicPath,
321
+ pathinfo: !prodBuild
322
+ },
323
+
324
+ optimization: {
325
+ noEmitOnErrors: true,
326
+
327
+ // Aggressive chunking strategy - produces chunks for any shared imports across JS apps.
328
+ splitChunks: {
329
+ chunks: 'all',
330
+ minSize: 0
331
+ },
332
+
333
+ // Improved debugging with readable module/chunk names.
334
+ namedChunks: true,
335
+ namedModules: true
336
+ },
337
+
338
+ resolve: {
339
+ alias: resolveAliases,
340
+ // Add JSX to support imports from .jsx source w/o needing to add the extension.
341
+ // Include "*" to continue supporting other imports that *do* specify an extension
342
+ // within the import statement (i.e. `import './foo.png'`). Yes, it's confusing.
343
+ extensions: ['*', '.js', '.jsx', '.json']
344
+ },
345
+
346
+ // Ensure Webpack can find loaders installed both within the top-level node_modules dir for
347
+ // an app that's building (standard case) or nested within dev-utils node_modules (in case
348
+ // of version conflict - triggered for us in Dec 2020 by postcss-loader version bump).
349
+ resolveLoader: {
350
+ modules: ['node_modules', devUtilsNodeModulesPath]
351
+ },
352
+
353
+ stats: stats,
354
+
355
+ module: {
356
+ // Flag missing exports as a failure vs. warning
357
+ strictExportPresence: true,
358
+
359
+ rules: [
360
+ {
361
+ oneOf: [
362
+
363
+ //------------------------
364
+ // Type mapping for .mjs files, used by the stylis library distribution.
365
+ // We have a transitive dep on stylis via: react-select > emotion > stylis
366
+ // Without this rule in place, builds fail with errors throw from emotion
367
+ // re. exports not found in stylis. Another user reported the same issue
368
+ // and provided this pointer @ https://github.com/thysultan/stylis.js/issues/254
369
+ //------------------------
370
+ {
371
+ test: /\.mjs$/,
372
+ type: 'javascript/auto'
373
+ },
374
+
375
+ //------------------------
376
+ // Image processing
377
+ // Encodes `url()` references directly when small enough.
378
+ //------------------------
379
+ {
380
+ test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
381
+ loader: 'url-loader',
382
+ options: {
383
+ limit: 10000,
384
+ name: 'static/media/[name].[hash:8].[ext]'
385
+ }
386
+ },
387
+
388
+ //------------------------
389
+ // JS processing
390
+ // Transpile via Babel, with presets/plugins to support Hoist's use of modern / staged JS features.
391
+ //------------------------
392
+ {
393
+ test: /\.(jsx?)$/,
394
+ use: {
395
+ loader: 'babel-loader',
396
+ options: {
397
+ presets: [
398
+ '@babel/preset-react',
399
+ [
400
+ '@babel/preset-env',
401
+ {
402
+ targets: targetBrowsers.join(', '),
403
+
404
+ // Specify use of corejs and allow it to polyfill proposals (e.g. object rest spread).
405
+ corejs: {version: 3, proposals: true},
406
+
407
+ // Note that we force import of core-js and regen-runtime in the `entry` config produced by this file.
408
+ // This should be replaced by a set of polyfills based on our target browsers as per this setting.
409
+ useBuiltIns: 'entry',
410
+
411
+ // Recently (Mar 2020) added optimization to preset-env to further minimize transpilation to ES5 where
412
+ // not required. See https://babeljs.io/docs/en/babel-preset-env#bugfixes.
413
+ bugfixes: true,
414
+
415
+ // Allow direct overrides from env config.
416
+ ...babelPresetEnvOptions
417
+ }
418
+ ]
419
+ ],
420
+ plugins: [
421
+ // Support our current decorator syntax, for MobX and Hoist decorators.
422
+ // See notes @ https://babeljs.io/docs/en/babel-plugin-proposal-decorators#legacy
423
+ ['@babel/plugin-proposal-decorators', {legacy: true}],
424
+
425
+ // Support classes level fields - must come after decorators plugin and be loose.
426
+ ['@babel/plugin-proposal-class-properties', {loose: true}],
427
+ // Must also configure private-* plugins below to config the "loose" setting
428
+ // to match plugin-proposal-class-properties.
429
+ ["@babel/plugin-proposal-private-methods", {loose: true}],
430
+ ["@babel/plugin-proposal-private-property-in-object", {loose: true}],
431
+
432
+ // Support `let x = foo?.bar`.
433
+ ['@babel/plugin-proposal-optional-chaining'],
434
+
435
+ // Support `let x = foo.bar ?? 'default'`.
436
+ ['@babel/plugin-proposal-nullish-coalescing-operator'],
437
+
438
+ // Avoid importing every FA icon ever made.
439
+ // See https://github.com/FortAwesome/react-fontawesome/issues/70
440
+ [require('babel-plugin-transform-imports'), {
441
+ '@fortawesome/pro-light-svg-icons': {
442
+ transform: '@fortawesome/pro-light-svg-icons/${member}',
443
+ skipDefaultConversion: true
444
+ },
445
+ '@fortawesome/pro-regular-svg-icons': {
446
+ transform: '@fortawesome/pro-regular-svg-icons/${member}',
447
+ skipDefaultConversion: true
448
+ },
449
+ '@fortawesome/pro-solid-svg-icons': {
450
+ transform: '@fortawesome/pro-solid-svg-icons/${member}',
451
+ skipDefaultConversion: true
452
+ },
453
+ '@fortawesome/free-brands-svg-icons': {
454
+ transform: '@fortawesome/free-brands-svg-icons/${member}',
455
+ skipDefaultConversion: true
456
+ }
457
+ }]
458
+ ],
459
+ // Cache for dev builds, don't bother compressing.
460
+ cacheDirectory: !prodBuild,
461
+ cacheCompression: false
462
+ }
463
+ },
464
+
465
+ // Always transpile Hoist - even when "packaged" we have the raw source as we are not
466
+ // currently transpiling anything in hoist-react on its own.
467
+ include: [srcPath, hoistPath, ...babelIncludePaths],
468
+ // In inline mode also *avoid* transpiling inline hoist's own node_modules libraries.
469
+ exclude: inlineHoist ? [hoistNodeModulesPath, ...babelExcludePaths] : babelExcludePaths
470
+ },
471
+
472
+
473
+ //------------------------
474
+ // SASS/CSS processing
475
+ // NOTE these loaders are applied in bottom-to-top (reverse) order.
476
+ //------------------------
477
+ {
478
+ test: /\.(sa|sc|c)ss$/,
479
+ use: [
480
+ // 3) Production builds use MiniCssExtractPlugin to break built styles into dedicated output files
481
+ // (vs. tags injected into DOM) for production builds. Note relies on MiniCssExtractPlugin being
482
+ // called within the prod plugins section.
483
+ prodBuild ? MiniCssExtractPlugin.loader : 'style-loader',
484
+
485
+ // 2) Resolve @imports within CSS, similar to module support in JS.
486
+ {
487
+ loader: 'css-loader',
488
+ options: {
489
+ importLoaders: 2, // Indicate how many prior loaders (postCssLoader/sassLoader) to also run on @imported resources.
490
+ sourceMap: true
491
+ }
492
+ },
493
+
494
+ // 1) Pre-process CSS to install flexbox bug workarounds + vendor-specific prefixes for the configured browsers
495
+ // Note that the "post" in the loader name refers to http://postcss.org/ - NOT the processing order within Webpack.
496
+ {
497
+ loader: 'postcss-loader',
498
+ options: {
499
+ postcssOptions: {
500
+ plugins: [
501
+ require('postcss-flexbugs-fixes'), // Inclusion of postcss-flexbugs-fixes is from CRA.
502
+ ['autoprefixer', {
503
+ // We still want to provide an array of target browsers
504
+ // that can be passed to / managed centrally by this script.
505
+ overrideBrowserslist: targetBrowsers,
506
+ flexbox: 'no-2009'
507
+ }]
508
+ ]
509
+ }
510
+ }
511
+ },
512
+
513
+ // 0) Process source SASS -> CSS
514
+ {loader: 'sass-loader'}
515
+ ]
516
+ },
517
+
518
+
519
+ //------------------------
520
+ // Fall-through entry to process all other assets via a file-loader.
521
+ // (Exclude config here is from CRA source config - commented there, but didn't understand).
522
+ //------------------------
523
+ {
524
+ exclude: [/\.jsx?$/, /\.html$/, /\.json$/],
525
+ loader: 'file-loader',
526
+ options: {
527
+ name: 'static/media/[name].[hash:8].[ext]'
528
+ }
529
+ }
530
+ ]
531
+ }
532
+ ].filter(Boolean)
533
+ },
534
+
535
+ plugins: [
536
+ // Clean (remove) the output directory before each run.
537
+ new CleanWebpackPlugin(),
538
+
539
+ // Load only the BlueprintJS icons used by Hoist-React components.
540
+ !loadAllBlueprintJsIcons ? new webpack.NormalModuleReplacementPlugin(
541
+ /.*\/generated\/iconSvgPaths.*/,
542
+ bpIconStubsPath,
543
+ ) : undefined,
544
+
545
+ // Inject global constants at compile time.
546
+ new webpack.DefinePlugin({
547
+ 'process.env': {NODE_ENV: JSON.stringify(process.env.NODE_ENV)},
548
+ xhAppCode: JSON.stringify(appCode),
549
+ xhAppName: JSON.stringify(appName),
550
+ xhAppVersion: JSON.stringify(appVersion),
551
+ xhAppBuild: JSON.stringify(appBuild),
552
+ xhBaseUrl: JSON.stringify(baseUrl),
553
+ xhAgGridLicenseKey: JSON.stringify(env.agGridLicenseKey),
554
+ xhBuildTimestamp: buildDate.getTime(),
555
+ xhIsDevelopmentMode: !prodBuild
556
+ }),
557
+
558
+ // Avoid bundling all moment.js locales and blowing up the bundle size
559
+ // See https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
560
+ new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
561
+
562
+
563
+ // Copy the /client-app/public directory and any contents into the build output if so
564
+ // configured. Also copy static preflight script if available.
565
+ new CopyWebpackPlugin({
566
+ patterns: _.compact([
567
+ copyPublicAssets ? {from: path.resolve(basePath, 'public'), to: 'public'} : undefined,
568
+ preflightScriptExists ? {from: preflightScriptPath, to: 'public'} : undefined
569
+ ])
570
+ }),
571
+
572
+ // Generate HTML index pages - one per JS app.
573
+ ...appNames.map(jsAppName => {
574
+ // Exclude all chunk combos not containing this app, which we currently generate as
575
+ // plugin doesn't have an include-by-regex feature (at least not one we have found).
576
+ const otherAppNames = appNames.filter(it => it !== jsAppName),
577
+ excludeAssets = getChunkCombinations(otherAppNames),
578
+ // Presence of preflight script indicates we can use the index template variant
579
+ // supplied by hoist-react *without* any inline scripts.
580
+ templateFilename = preflightScriptExists ? 'index-no-inline.html' : 'index.html';
581
+
582
+ return new HtmlWebpackPlugin({
583
+ title: appName,
584
+ // Note: HTML template is sourced from hoist-react.
585
+ template: path.resolve(hoistPath, `static/${templateFilename}`),
586
+ filename: `${jsAppName}/index.html`,
587
+ excludeChunks: excludeAssets,
588
+ minify: false // no need to minify the HTML itself
589
+ });
590
+ }),
591
+
592
+ // Insert a script tag for the (unbundled) preflight script, before all other scripts.
593
+ preflightScriptExists ? new HtmlWebpackTagsPlugin({
594
+ // Script available at this path via CopyWebpackPlugin above.
595
+ scripts: ['public/preflight.js'],
596
+ append: false,
597
+ hash: true
598
+ }) : undefined,
599
+
600
+ // Generate favicons from source image if provided - injected into generated HTML.
601
+ favicon ? new FaviconsWebpackPlugin({
602
+ logo: favicon,
603
+ prefix: 'icons-[hash:8]/',
604
+ inject: true,
605
+ mode: 'webapp',
606
+ // Available options @ https://github.com/itgalaxy/favicons#usage
607
+ favicons: {
608
+ appName: appName,
609
+ appDescription: appName,
610
+ version: appVersion,
611
+ theme_color: '#212121', // off-black from default `--xh-black` CSS var
612
+ appleStatusBarStyle: 'black',
613
+ start_url: '/',
614
+ icons: {
615
+ android: true,
616
+ appleIcon: true,
617
+ appleStartup: false,
618
+ coast: false,
619
+ favicons: true,
620
+ firefox: false,
621
+ windows: true,
622
+ yandex: false
623
+ },
624
+ ...faviconManifestConfig
625
+ }
626
+ }) : undefined,
627
+
628
+ // Support an optional post-build/run interactive treemap of output bundles and their sizes / contents.
629
+ analyzeBundles ? new BundleAnalyzerPlugin({
630
+ analyzerMode: 'server'
631
+ }) : undefined,
632
+
633
+ // Warn on dupe package included in bundle due to multiple, conflicting versions.
634
+ checkForDupePackages ? new DuplicatePackageCheckerPlugin({
635
+ verbose: true,
636
+ showHelp: false,
637
+ strict: false,
638
+ exclude: (instance) => dupePackageCheckExcludes.includes(instance.name)
639
+ }) : undefined,
640
+
641
+ // Display build progress - enable profile for per-loader/file type stats.
642
+ new WebpackBar({
643
+ color: '#ec7316',
644
+ profile: true
645
+ }),
646
+
647
+ // Environment-specific plugins.
648
+ ...(prodBuild ? extraPluginsProd(terserOptions, devtool) : extraPluginsDev())
649
+
650
+ ].filter(Boolean),
651
+
652
+ devtool: devtool,
653
+
654
+ // Inline dev-time configuration for webpack-dev-server.
655
+ devServer: prodBuild ? undefined : {
656
+ https: devHttps,
657
+ host: devHost,
658
+ port: devWebpackPort,
659
+ overlay: true,
660
+ compress: true,
661
+ hot: true,
662
+ noInfo: true,
663
+ stats: stats,
664
+ open: env.devServerOpenPage != null,
665
+ openPage: env.devServerOpenPage,
666
+ // Support HTML5 history routes for apps, with /appName/ as the base route for each
667
+ historyApiFallback: {
668
+ rewrites: appNames.map(appName => {
669
+ return {
670
+ from: new RegExp(`^/${appName}`),
671
+ to: `/${appName}/index.html`
672
+ };
673
+ })
674
+ }
675
+ }
676
+ };
677
+ }
678
+
679
+
680
+ //------------------------
681
+ // Implementation
682
+ //------------------------
683
+ const extraPluginsProd = (terserOptions, devtool) => {
684
+ return [
685
+ // Extract built CSS files into sub-directories by chunk / entry point name.
686
+ new MiniCssExtractPlugin({
687
+ filename: '[name]/[name].[contenthash:8].css'
688
+ }),
689
+
690
+ // Minify and tree-shake via Terser - https://github.com/terser/terser#readme
691
+ new TerserPlugin({
692
+ sourceMap: !!devtool,
693
+ terserOptions: {
694
+ // Mangling disabled due to intermittent / difficult to debug issues with it
695
+ // breaking code, especially when run on already-packaged libraries. Disabling does
696
+ // increase bundle size, although not by much on a relative basis.
697
+ mangle: false,
698
+ // As per docs "prevent discarding or mangling of function names" - most likely not
699
+ // necessary w/mangling off, but leaving here as docs are a bit vague, and in case
700
+ // we re-enable. We want to maintain function/class names for error messages.
701
+ keep_fnames: true,
702
+
703
+ compress: {
704
+ comparisons: false,
705
+ // See https://fontawesome.com/how-to-use/with-the-api/other/tree-shaking
706
+ collapse_vars: false
707
+ },
708
+ ...terserOptions
709
+ }
710
+ })
711
+ ];
712
+ };
713
+
714
+ const extraPluginsDev = () => {
715
+ return [
716
+ // Avoid dev-time errors with mis-matched casing in imports (where a less case sensitive OS
717
+ // will resolve OK, but import could fail at build time with strict case sensitivity).
718
+ new CaseSensitivePathsPlugin(),
719
+
720
+ // For HMR
721
+ new webpack.HotModuleReplacementPlugin()
722
+ ];
723
+ };
724
+
725
+ // Generate combinations for given chunkNames so we can pass them as excludes to HtmlWebpackPlugin
726
+ // where this is called. This will be passed the names of all the apps we *do not* want to load
727
+ // from the HTML index page we are building and will output their possible chunk combos to exclude.
728
+ //
729
+ // Unclear if this is really a valid approach, but it seems to work. Relies on the fact that chunk
730
+ // combos are named according to alpha-ordered entry points included (as well as "vendors" for
731
+ // library dependencies). So given a list of apps such as [admin, app, mobile], possible chunk
732
+ // combos will be of the form vendors~admin, vendors~admin~app, vendors~app~mobile, and so on...
733
+ //
734
+ function getChunkCombinations(chunkNames) {
735
+ // Add 'vendors' to also generate 'vendors~fooApp~barApp' chunk paths for exclusion.
736
+ chunkNames = ['vendors', ...chunkNames];
737
+
738
+ let result = [];
739
+ let f = function(path, chunkNames) {
740
+ for (let i = 0; i < chunkNames.length; i++) {
741
+ const sep = path === '' ? '' : '~',
742
+ newPath = path + sep + chunkNames[i];
743
+ result.push(newPath);
744
+ f(newPath, chunkNames.slice(i + 1));
745
+ }
746
+ };
747
+ f('', chunkNames);
748
+ return result.filter(chunk => chunk !== 'vendors');
749
+ }
750
+
751
+ function logSep() {console.log(':------------------------------------')}
752
+ function logMsg(msg) {console.log(`: ${msg}`)}
753
+
754
+ module.exports = configureWebpack;