/
create-webpack-config.js
543 lines (498 loc) · 16.9 KB
/
create-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
533
534
535
536
537
538
539
540
541
542
543
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin-patch');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const autoprefixer = require('autoprefixer');
const postcssDiscardDuplicates = require('postcss-discard-duplicates');
const ManifestPlugin = require('webpack-manifest-plugin');
const fs = require('fs');
const deepmerge = require('deepmerge');
const resolve = require('resolve');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
const npmSass = require('npm-sass');
const merge = require('webpack-merge');
const SassDocPlugin = require('@bolt/sassdoc-webpack-plugin');
const { getConfig } = require('@bolt/build-utils/config-store');
const { boltWebpackProgress } = require('@bolt/build-utils/webpack-helpers');
const {
webpackStats,
statsPreset,
} = require('@bolt/build-utils/webpack-verbosity');
const {
getBoltManifest,
mapComponentNameToTwigNamespace,
} = require('@bolt/build-utils/manifest');
const log = require('@bolt/build-utils/log');
// Store set of webpack configs used in multiple builds
let webpackConfigs = [];
async function createWebpackConfig(buildConfig) {
const config = buildConfig;
const fullBuildConfig = await getConfig();
// The publicPath config sets the client-side base path for all built / asynchronously loaded assets. By default the loader script will automatically figure out the relative path to load your components, but uses publicPath as a fallback. It's recommended to have it start with a `/`. Note: this ONLY sets the base path the browser requests -- it does not set where files are saved during build. To change where files are saved at build time, use the buildDir config.
// Must start and end with `/`
// conditional is temp workaround for when servers are disabled via absence of `config.wwwDir`
const publicPath = config.publicPath
? config.publicPath
: config.wwwDir
? `/${path.relative(config.wwwDir, config.buildDir)}/`
: config.buildDir; // @todo Ensure ends with `/` or we can get `distfonts/` instead of `dist/fonts/`
// @TODO: move this setting to .boltrc config
const sassExportData = require('@bolt/sass-export-data')({
path: config.dataDir,
});
// map out Twig namespaces with the NPM package name
const npmToTwigNamespaceMap = await mapComponentNameToTwigNamespace();
// filename suffix to tack on based on lang being compiled for
let langSuffix = `${config.lang ? '-' + config.lang : ''}`;
let themifyOptions = {
watchForChanges:
config.watch === true && config.mode !== 'server' ? true : false,
classPrefix: 't-bolt-',
screwIE11: config.mode === 'server' ? true : false,
fallback: {
filename: 'bolt-css-vars-fallback',
jsonDataExport: 'theming-css-vars',
},
};
themifyOptions = deepmerge(themifyOptions, {
fallback: {
jsonPath: path.resolve(
config.buildDir,
`data/${themifyOptions.fallback.jsonDataExport}.json`,
),
cssPath: path.resolve(
config.buildDir,
`${themifyOptions.fallback.filename}.css`,
),
},
});
// Default global Sass data defined
let globalSassData = [
`$bolt-namespace: ${config.namespace};`,
`$bolt-css-vars-json-data-export: ${themifyOptions.fallback.jsonDataExport};`,
// output $bolt-lang variable in Sass even if not specified so things fall back accordingly.
`${config.lang ? `$bolt-lang: ${config.lang};` : '$bolt-lang: null;'}`,
];
// Default global JS data defined
let globalJsData = {
'process.env.NODE_ENV': config.prod
? JSON.stringify('production')
: JSON.stringify('development'),
bolt: {
mode: JSON.stringify(config.mode),
isClient: config.mode === 'client' ? true : false,
isServer: config.mode === 'server' ? true : false,
namespace: JSON.stringify(config.namespace),
themingFallbackCSS: JSON.stringify(
publicPath + themifyOptions.fallback.filename + '.css',
),
config: {
prod: config.prod ? true : false,
lang: JSON.stringify(config.lang),
env: JSON.stringify(config.env),
},
},
};
// Merge together global Sass data overrides specified in a .boltrc config
if (config.globalData.scss && config.globalData.scss.length !== 0) {
const overrideItems = [];
config.globalData.scss.forEach(item => {
try {
const file = fs.readFileSync(item, 'utf8');
file
.split('\n')
.filter(x => x)
.forEach(x => overrideItems.push(x));
} catch (err) {
log.errorAndExit(`Could not find ${item}`, err);
}
});
globalSassData = [...globalSassData, ...overrideItems];
}
// Merge together any global JS data overrides
if (config.globalData.js && config.globalData.js.length !== 0) {
const overrideJsItems = [];
config.globalData.js.forEach(item => {
try {
const overrideFile = require(path.resolve(process.cwd(), item));
overrideJsItems.push(overrideFile);
} catch (err) {
log.errorAndExit(`Could not find ${item} file`, err);
}
});
globalJsData = deepmerge(globalJsData, ...overrideJsItems);
}
/**
* Build WebPack config's `entry` object
* @link https://webpack.js.org/configuration/entry-context/#entry
* @returns {object} entry - WebPack config `entry`
*/
async function buildWebpackEntry() {
const { components } = await getBoltManifest();
const entry = {};
const globalEntryName = 'bolt-global';
if (components.global) {
entry[globalEntryName] = ['@bolt/core/styles/index.scss'];
components.global.forEach(component => {
if (component.assets.style) {
entry[globalEntryName].push(component.assets.style);
}
if (component.assets.main) {
entry[globalEntryName].push(component.assets.main);
}
});
const useHotMiddleware =
Array.isArray(fullBuildConfig.lang) && fullBuildConfig.lang.length > 1
? false
: true;
if (!config.prod && config.webpackDevServer && useHotMiddleware) {
entry[globalEntryName].push(
`webpack-hot-middleware/client?name=${config.lang}&noInfo=true&quiet=true&logLevel=silent&reload=true`,
);
}
}
if (components.individual) {
components.individual.forEach(component => {
const files = [];
if (component.assets.style) files.push(component.assets.style);
if (component.assets.main) files.push(component.assets.main);
if (files) {
entry[component.basicName] = files;
}
});
}
if (config.verbosity > 4) {
log.info('WebPack `entry`:');
console.log(entry);
}
return entry;
}
const scssLoaders = [
{
loader: 'css-loader',
options: {
sourceMap: config.sourceMaps,
modules: false, // needed for JS referencing classNames directly, such as critical fonts
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: config.sourceMaps,
plugins: () => [
require('@bolt/postcss-themify')(themifyOptions),
postcssDiscardDuplicates,
autoprefixer({
grid: true,
}),
],
},
},
{
loader: 'clean-css-loader',
options: {
level: config.prod ? 2 : 0,
format: config.prod ? false : 'beautify',
inline: ['remote'],
},
},
{
loader: 'resolve-url-loader',
},
{
loader: 'sass-loader',
options: {
sourceMap: config.sourceMaps,
importer: [npmSass.importer],
functions: sassExportData,
precision: 3,
data: globalSassData.join('\n'),
outputStyle: 'nested',
},
},
];
let webpackConfig = {
target: 'web',
entry: await buildWebpackEntry(),
output: {
path: path.resolve(process.cwd(), config.buildDir),
// @todo: switch this to output .client.js and .server.js file prefixes when we hit Bolt v3.0
filename: `[name]${langSuffix}${
config.mode !== 'client' ? `.${config.mode}` : ''
}.js`,
chunkFilename: `[name]-bundle${langSuffix}-[chunkhash].js`,
publicPath,
},
resolve: {
mainFields: ['esnext', 'jsnext:main', 'browser', 'module', 'main'],
extensions: [
'.js',
'.jsx',
'.mjs',
'.json',
'.svg',
'.scss',
'.ts',
'.tsx',
],
alias: {
react: 'preact-compat',
'react-dom': 'preact-compat',
},
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
{
test: /\.scss$/,
oneOf: [
{
issuer: /\.js$/,
use: [scssLoaders].reduce((acc, val) => acc.concat(val), []),
},
{
// no issuer here as it has a bug when its an entry point - https://github.com/webpack/webpack/issues/5906
use: [
// 'css-hot-loader',
MiniCssExtractPlugin.loader,
scssLoaders,
].reduce((acc, val) => acc.concat(val), []),
},
],
},
{
test: /\.(js|tsx|mjs)$/,
exclude: /(node_modules\/\@webcomponents\/webcomponentsjs\/custom-elements-es5-adapter\.js)/,
use: {
loader: 'babel-loader',
options: {
babelrc: false,
cacheDirectory: true,
presets: ['@bolt/babel-preset-bolt'],
},
},
},
{
test: /\.(woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 500,
name: 'fonts/[name].[ext]',
},
},
{
test: /\.(cur|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
{
test: [/\.yml$/, /\.yaml$/],
use: [{ loader: 'json-loader' }, { loader: 'yaml-loader' }],
},
],
},
mode: config.prod ? 'production' : 'development',
// optimization: {
// mergeDuplicateChunks: true,
// },
optimization: {
minimizer: config.prod
? [
new UglifyJsPlugin({
sourceMap: true,
parallel: true,
cache: true,
uglifyOptions: {
compress: true,
mangle: true,
output: {
comments: false,
beautify: false,
},
},
}),
]
: [],
},
plugins: [
new webpack.ProgressPlugin(boltWebpackProgress), // Ties together the Bolt custom Webpack messages + % complete
new WriteFilePlugin(),
new MiniCssExtractPlugin({
filename: `[name]${langSuffix}.css`,
chunkFilename: `[id]${langSuffix}.css`,
}),
// @todo This needs to be in `config.dataDir`
new ManifestPlugin({
fileName: `bolt-webpack-manifest${langSuffix}${
config.mode === 'client' ? '' : `.${config.mode}`
}.json`,
publicPath,
writeToFileEmit: true,
seed: {
name: 'Bolt Manifest',
},
}),
new webpack.DefinePlugin(globalJsData),
new webpack.NamedModulesPlugin(),
new CopyWebpackPlugin(config.copy ? config.copy : []),
],
};
if (config.mode !== 'server') {
webpackConfig.plugins.push(
new SassDocPlugin(
{
src: `${path.dirname(resolve.sync('@bolt/core'))}/styles/`,
dest: path.resolve(`${config.dataDir}/sassdoc.bolt.json`),
},
{
outputPath: config.buildDir,
},
),
);
}
if (!config.prod && config.webpackDevServer) {
webpackConfig.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
);
}
// Enable new experimental cache mode to significantly speed up the initial build times
// if (config.enableCache && !config.prod) {
if (config.enableCache) {
webpackConfig.plugins.push(
new HardSourceWebpackPlugin({
info: {
level: 'warn',
},
// Clean up large, old caches automatically.
cachePrune: {
// Caches younger than `maxAge` are not considered for deletion. They must
// be at least this (default: 2 days) old in milliseconds.
maxAge: 2 * 24 * 60 * 60 * 1000,
// All caches together must be larger than `sizeThreshold` before any
// caches will be deleted. Together they must be at least 300MB in size
sizeThreshold: 300 * 1024 * 1024,
},
}),
);
}
if (config.prod) {
// Optimize JS - https://webpack.js.org/plugins/uglifyjs-webpack-plugin/
// Config recommendation based off of https://slack.engineering/keep-webpack-fast-a-field-guide-for-better-build-performance-f56a5995e8f1#f548
webpackConfig.plugins.push(
new UglifyJsPlugin({
sourceMap: config.sourceMaps,
parallel: true,
cache: true,
uglifyOptions: {
compress: true,
mangle: true,
},
}),
);
// https://webpack.js.org/plugins/module-concatenation-plugin/
webpackConfig.plugins.push(
new webpack.optimize.ModuleConcatenationPlugin(),
);
// Optimize CSS - https://github.com/NMFR/optimize-css-assets-webpack-plugin
webpackConfig.plugins.push(
new OptimizeCssAssetsPlugin({
canPrint: config.verbosity > 2,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: [
'default',
{
discardComments: { removeAll: true },
mergeLonghand: false, // don't merge longhand values -- required for CSS Vars theming, etc.
zindex: false, // don't alter `z-index` values
mergeRules: false, // this MUST be disabled - otherwise certain selectors (ex. ::slotted(*), which IE 11 can't parse) break
},
],
},
}),
);
// @todo evaluate best source map approach for production builds -- particularly source-map vs hidden-source-map
webpackConfig.devtool =
config.sourceMaps === false ? '' : 'hidden-source-map';
} else {
// not prod
// @todo fix source maps
webpackConfig.devtool =
config.sourceMaps === false ? '' : 'eval-source-map';
}
if (config.wwwDir) {
webpackConfig.devServer = {
logLevel: 'silent',
log: false,
overlayWarnings: true,
overlay: true,
quiet: true,
clientLogLevel: 'none',
stats: statsPreset(webpackStats[config.verbosity]),
hot: config.prod ? false : true,
noInfo: true, // webpackTasks.watch handles output info related to success & failure
publicPath,
};
}
// Simple Configuration
// The easiest way to tweak the Bolt webpack config is by providing an object to the configureWebpack option in the `.boltrc.js` config:
// // .boltrc.js
// module.exports = {
// configureWebpack: {
// plugins: [
// new MyAwesomeWebpackPlugin()
// ]
// }
// }
// The object will be merged into the final webpack config using webpack-merge.
if (config.configureWebpack) {
webpackConfig = merge(webpackConfig, config.configureWebpack);
}
return webpackConfig;
}
// Helper function to associate each unique language in the build config with a separate Webpack build instance (making filenames, etc unique);
async function assignLangToWebpackConfig(config, lang) {
let langSpecificConfig = config;
if (lang) {
langSpecificConfig.lang = lang; // Make sure only ONE language config is set per Webpack build instance.
}
let langSpecificWebpackConfig = await createWebpackConfig(langSpecificConfig);
if (langSpecificConfig.webpackStats) {
langSpecificWebpackConfig.profile = true;
langSpecificWebpackConfig.parallelism = 1;
}
webpackConfigs.push(langSpecificWebpackConfig);
}
module.exports = async function() {
const config = await getConfig();
return new Promise(async (resolve, reject) => {
const langs = config.lang;
const promises = [];
// update the array of Webpack configs so each config is assigned to only one language (used in the filename's suffix when bundling language-tailed CSS and JS)
if (Array.isArray(langs)) {
for (const lang of langs) {
/* eslint-disable no-await-in-loop */
promises.push(await assignLangToWebpackConfig(config, lang));
}
} else if (langs === 'en') {
promises.push(await assignLangToWebpackConfig(config, null));
} else {
promises.push(await assignLangToWebpackConfig(config, config.lang));
}
await Promise.all(promises).then(() => {
return resolve(webpackConfigs);
});
});
};