forked from symfony/webpack-encore
/
WebpackConfig.js
799 lines (641 loc) · 28.3 KB
/
WebpackConfig.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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/*
* This file is part of the Symfony Webpack Encore package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
'use strict';
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const logger = require('./logger');
/**
* @param {RuntimeConfig} runtimeConfig
* @return {void}
*/
function validateRuntimeConfig(runtimeConfig) {
// if you're using the encore executable, these things should never happen
if (null === runtimeConfig.context) {
throw new Error('RuntimeConfig.context must be set.');
}
if (null === runtimeConfig.babelRcFileExists) {
throw new Error('RuntimeConfig.babelRcFileExists must be set.');
}
}
class WebpackConfig {
constructor(runtimeConfig) {
validateRuntimeConfig(runtimeConfig);
this.runtimeConfig = runtimeConfig;
this.entries = new Map();
this.styleEntries = new Map();
this.plugins = [];
this.loaders = [];
// Global settings
this.outputPath = null;
this.publicPath = null;
this.manifestKeyPrefix = null;
this.sharedCommonsEntryName = null;
this.sharedCommonsEntryFile = null;
this.providedVariables = {};
this.configuredFilenames = {};
this.aliases = {};
this.externals = [];
this.integrityAlgorithms = [];
// Features/Loaders flags
this.useVersioning = false;
this.useSourceMaps = false;
this.cleanupOutput = false;
this.extractCss = true;
this.useImagesLoader = true;
this.useFontsLoader = true;
this.usePostCssLoader = false;
this.useLessLoader = false;
this.useStylusLoader = false;
this.useSassLoader = false;
this.useReact = false;
this.usePreact = false;
this.useVueLoader = false;
this.useEslintLoader = false;
this.useTypeScriptLoader = false;
this.useForkedTypeScriptTypeChecking = false;
this.useWebpackNotifier = false;
this.useHandlebarsLoader = false;
// Features/Loaders options
this.copyFilesConfigs = [];
this.sassOptions = {
resolveUrlLoader: true
};
this.preactOptions = {
preactCompat: false
};
this.urlLoaderOptions = {
images: false,
fonts: false
};
this.babelOptions = {
exclude: /(node_modules|bower_components)/,
useBuiltIns: 'entry',
};
// Features/Loaders options callbacks
this.postCssLoaderOptionsCallback = () => {};
this.sassLoaderOptionsCallback = () => {};
this.lessLoaderOptionsCallback = () => {};
this.stylusLoaderOptionsCallback = () => {};
this.babelConfigurationCallback = () => {};
this.cssLoaderConfigurationCallback = () => {};
this.shouldUseSingleRuntimeChunk = null;
this.shouldSplitEntryChunks = false;
this.splitChunksConfigurationCallback = () => {};
this.watchOptionsConfigurationCallback = () => {};
this.vueLoaderOptionsCallback = () => {};
this.eslintLoaderOptionsCallback = () => {};
this.tsConfigurationCallback = () => {};
this.handlebarsConfigurationCallback = () => {};
this.loaderConfigurationCallbacks = {
javascript: () => {},
css: () => {},
images: () => {},
fonts: () => {},
sass: () => {},
less: () => {},
stylus: () => {},
vue: () => {},
eslint: () => {},
typescript: () => {},
handlebars: () => {},
};
// Plugins options
this.cleanWebpackPluginPaths = ['**/*'];
// Plugins callbacks
this.cleanWebpackPluginOptionsCallback = () => {};
this.definePluginOptionsCallback = () => {};
this.forkedTypeScriptTypesCheckOptionsCallback = () => {};
this.friendlyErrorsPluginOptionsCallback = () => {};
this.manifestPluginOptionsCallback = () => {};
this.terserPluginOptionsCallback = () => {};
this.optimizeCssPluginOptionsCallback = () => {};
this.notifierPluginOptionsCallback = () => {};
}
getContext() {
return this.runtimeConfig.context;
}
doesBabelRcFileExist() {
return this.runtimeConfig.babelRcFileExists;
}
setOutputPath(outputPath) {
if (!path.isAbsolute(outputPath)) {
outputPath = path.resolve(this.getContext(), outputPath);
}
if (!fs.existsSync(outputPath)) {
// If the parent of the output directory does not exist either
// check if it is located under the context directory before
// creating it and its parent.
const parentPath = path.dirname(outputPath);
if (!fs.existsSync(parentPath)) {
const context = path.resolve(this.getContext());
if (outputPath.indexOf(context) !== 0) {
throw new Error(`outputPath directory "${outputPath}" does not exist and is not located under the context directory "${context}". Please check the path you're passing to setOutputPath() or create this directory.`);
}
parentPath.split(path.sep).reduce((previousPath, directory) => {
const newPath = path.resolve(previousPath, directory);
if (!fs.existsSync(newPath)) {
fs.mkdirSync(newPath);
}
return newPath;
}, path.sep);
}
fs.mkdirSync(outputPath);
}
this.outputPath = outputPath;
}
setPublicPath(publicPath) {
if (publicPath.includes('://') === false && publicPath.indexOf('/') !== 0) {
// technically, not starting with "/" is legal, but not
// what you want in most cases. Let's warn the user that
// they might be making a mistake.
logger.warning('The value passed to setPublicPath() should *usually* start with "/" or be a full URL (http://...). If you\'re not sure, then you should probably change your public path and make this message disappear.');
}
// guarantee a single trailing slash
publicPath = publicPath.replace(/\/$/,'');
publicPath = publicPath + '/';
this.publicPath = publicPath;
}
setManifestKeyPrefix(manifestKeyPrefix) {
/*
* Normally, we make sure that the manifest keys don't start
* with an opening "/" ever... for consistency. If you need
* to manually specify the manifest key (e.g. because you're
* publicPath is absolute), it's easy to accidentally add
* an opening slash (thereby changing your key prefix) without
* intending to. Hence, the warning.
*/
if (manifestKeyPrefix.indexOf('/') === 0) {
logger.warning(`The value passed to setManifestKeyPrefix "${manifestKeyPrefix}" starts with "/". This is allowed, but since the key prefix does not normally start with a "/", you may have just changed the prefix accidentally.`);
}
// guarantee a single trailing slash, except for blank strings
if (manifestKeyPrefix !== '') {
manifestKeyPrefix = manifestKeyPrefix.replace(/\/$/, '');
manifestKeyPrefix = manifestKeyPrefix + '/';
}
this.manifestKeyPrefix = manifestKeyPrefix;
}
configureDefinePlugin(definePluginOptionsCallback = () => {}) {
if (typeof definePluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureDefinePlugin() must be a callback function');
}
this.definePluginOptionsCallback = definePluginOptionsCallback;
}
configureFriendlyErrorsPlugin(friendlyErrorsPluginOptionsCallback = () => {}) {
if (typeof friendlyErrorsPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureFriendlyErrorsPlugin() must be a callback function');
}
this.friendlyErrorsPluginOptionsCallback = friendlyErrorsPluginOptionsCallback;
}
configureManifestPlugin(manifestPluginOptionsCallback = () => {}) {
if (typeof manifestPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureManifestPlugin() must be a callback function');
}
this.manifestPluginOptionsCallback = manifestPluginOptionsCallback;
}
configureTerserPlugin(terserPluginOptionsCallback = () => {}) {
if (typeof terserPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureTerserPlugin() must be a callback function');
}
this.terserPluginOptionsCallback = terserPluginOptionsCallback;
}
configureOptimizeCssPlugin(optimizeCssPluginOptionsCallback = () => {}) {
if (typeof optimizeCssPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureOptimizeCssPlugin() must be a callback function');
}
this.optimizeCssPluginOptionsCallback = optimizeCssPluginOptionsCallback;
}
/**
* Returns the value that should be used as the publicPath,
* which can be overridden by enabling the webpackDevServer
*
* @returns {string}
*/
getRealPublicPath() {
if (!this.useDevServer()) {
return this.publicPath;
}
if (this.runtimeConfig.devServerKeepPublicPath) {
return this.publicPath;
}
if (this.publicPath.includes('://')) {
return this.publicPath;
}
// if using dev-server, prefix the publicPath with the dev server URL
return this.runtimeConfig.devServerUrl.replace(/\/$/,'') + this.publicPath;
}
addEntry(name, src) {
if (this.entries.has(name)) {
throw new Error(`Duplicate name "${name}" passed to addEntry(): entries must be unique.`);
}
// also check for styleEntries duplicates
if (this.styleEntries.has(name)) {
throw new Error(`The "${name}" passed to addEntry conflicts with a name passed to addStyleEntry(). The entry names between addEntry() and addStyleEntry() must be unique.`);
}
this.entries.set(name, src);
}
addStyleEntry(name, src) {
if (this.styleEntries.has(name)) {
throw new Error(`Duplicate name "${name}" passed to addStyleEntry(): entries must be unique.`);
}
// also check for entries duplicates
if (this.entries.has(name)) {
throw new Error(`The "${name}" passed to addStyleEntry() conflicts with a name passed to addEntry(). The entry names between addEntry() and addStyleEntry() must be unique.`);
}
this.styleEntries.set(name, src);
}
addPlugin(plugin, priority = 0) {
if (typeof priority !== 'number') {
throw new Error('Argument 2 to addPlugin() must be a number.');
}
this.plugins.push({
plugin: plugin,
priority: priority
});
}
addLoader(loader) {
this.loaders.push(loader);
}
addAliases(aliases = {}) {
if (typeof aliases !== 'object') {
throw new Error('Argument 1 to addAliases() must be an object.');
}
Object.assign(this.aliases, aliases);
}
addExternals(externals = []) {
if (!Array.isArray(externals)) {
externals = [externals];
}
this.externals = this.externals.concat(externals);
}
enableVersioning(enabled = true) {
this.useVersioning = enabled;
}
enableSourceMaps(enabled = true) {
this.useSourceMaps = enabled;
}
configureBabel(callback, options = {}) {
if (typeof callback !== 'function') {
throw new Error('Argument 1 to configureBabel() must be a callback function.');
}
if (this.doesBabelRcFileExist()) {
throw new Error('configureBabel() cannot be called because your app already has Babel configuration (a `.babelrc` file, `.babelrc.js` file or `babel` key in `package.json`). Either put all of your Babel configuration in that file, or delete it and use this function.');
}
this.babelConfigurationCallback = callback;
for (const optionKey of Object.keys(options)) {
let normalizedOptionKey = optionKey;
if (optionKey === 'include_node_modules') {
logger.deprecation('configureBabel: "include_node_modules" is deprecated. Please use "includeNodeModules" instead.');
normalizedOptionKey = 'includeNodeModules';
}
if (normalizedOptionKey === 'includeNodeModules') {
if (Object.keys(options).includes('exclude')) {
throw new Error('"includeNodeModules" and "exclude" options can\'t be used together when calling configureBabel().');
}
if (!Array.isArray(options[optionKey])) {
throw new Error('Option "includeNodeModules" passed to configureBabel() must be an Array.');
}
this.babelOptions['exclude'] = (filePath) => {
// Don't exclude modules outside of node_modules/bower_components
if (!/(node_modules|bower_components)/.test(filePath)) {
return false;
}
// Don't exclude whitelisted Node modules
const whitelistedModules = options[optionKey].map(
module => path.join('node_modules', module) + path.sep
);
for (const modulePath of whitelistedModules) {
if (filePath.includes(modulePath)) {
return false;
}
}
// Exclude other modules
return true;
};
} else if (!(normalizedOptionKey in this.babelOptions)) {
throw new Error(`Invalid option "${normalizedOptionKey}" passed to configureBabel(). Valid keys are ${[...Object.keys(this.babelOptions), 'includeNodeModules'].join(', ')}`);
} else {
this.babelOptions[normalizedOptionKey] = options[optionKey];
}
}
}
configureCssLoader(callback) {
if (typeof callback !== 'function') {
throw new Error('Argument 1 to configureCssLoader() must be a callback function.');
}
this.cssLoaderConfigurationCallback = callback;
}
enableSingleRuntimeChunk() {
this.shouldUseSingleRuntimeChunk = true;
}
disableSingleRuntimeChunk() {
this.shouldUseSingleRuntimeChunk = false;
}
splitEntryChunks() {
if (this.sharedCommonsEntryName) {
throw new Error('Using splitEntryChunks() and createSharedEntry() together is not supported. Use one of these strategies only to optimize your build.');
}
this.shouldSplitEntryChunks = true;
}
configureSplitChunks(callback) {
if (typeof callback !== 'function') {
throw new Error('Argument 1 to configureSplitChunks() must be a callback function.');
}
this.splitChunksConfigurationCallback = callback;
}
configureWatchOptions(callback) {
if (typeof callback !== 'function') {
throw new Error('Argument 1 to configureWatchOptions() must be a callback function.');
}
this.watchOptionsConfigurationCallback = callback;
}
createSharedEntry(name, file) {
if (this.shouldSplitEntryChunks) {
throw new Error('Using splitEntryChunks() and createSharedEntry() together is not supported. Use one of these strategies only to optimize your build.');
}
// don't allow to call this twice
if (this.sharedCommonsEntryName) {
throw new Error('createSharedEntry() cannot be called multiple times: you can only create *one* shared entry.');
}
if (Array.isArray(file)) {
throw new Error('Argument 2 to createSharedEntry() must be a single string file: not an array of files. Try creating one file that requires/imports all the modules that should be included.');
}
this.sharedCommonsEntryName = name;
this.sharedCommonsEntryFile = file;
this.addEntry(name, file);
}
copyFiles(configs = []) {
if (!Array.isArray(configs)) {
configs = [configs];
}
if (configs.some(elt => typeof elt !== 'object')) {
throw new Error('copyFiles() must be called with either a config object or an array of config objects.');
}
const defaultConfig = {
from: null,
pattern: /.*/,
to: null,
includeSubdirectories: true,
context: null,
};
for (const config of configs) {
if (!config.from) {
throw new Error('Config objects passed to copyFiles() must have a "from" property.');
}
for (const configKey of Object.keys(config)) {
if (!(configKey in defaultConfig)) {
throw new Error(`Invalid config option "${configKey}" passed to copyFiles(). Valid keys are ${Object.keys(defaultConfig).join(', ')}`);
}
}
if (typeof config.pattern !== 'undefined' && !(config.pattern instanceof RegExp)) {
let validPattern = false;
if (typeof config.pattern === 'string') {
const regexPattern = /^\/(.*)\/([a-z]*)?$/;
if (regexPattern.test(config.pattern)) {
validPattern = true;
}
}
if (!validPattern) {
throw new Error(`Invalid pattern "${config.pattern}" passed to copyFiles(). Make sure it contains a valid regular expression.`);
}
}
this.copyFilesConfigs.push(
Object.assign({}, defaultConfig, config)
);
}
}
enablePostCssLoader(postCssLoaderOptionsCallback = () => {}) {
this.usePostCssLoader = true;
if (typeof postCssLoaderOptionsCallback !== 'function') {
throw new Error('Argument 1 to enablePostCssLoader() must be a callback function.');
}
this.postCssLoaderOptionsCallback = postCssLoaderOptionsCallback;
}
enableSassLoader(sassLoaderOptionsCallback = () => {}, options = {}) {
this.useSassLoader = true;
if (typeof sassLoaderOptionsCallback !== 'function') {
throw new Error('Argument 1 to enableSassLoader() must be a callback function.');
}
this.sassLoaderOptionsCallback = sassLoaderOptionsCallback;
for (const optionKey of Object.keys(options)) {
let normalizedOptionKey = optionKey;
if (optionKey === 'resolve_url_loader') {
logger.deprecation('enableSassLoader: "resolve_url_loader" is deprecated. Please use "resolveUrlLoader" instead.');
normalizedOptionKey = 'resolveUrlLoader';
}
if (!(normalizedOptionKey in this.sassOptions)) {
throw new Error(`Invalid option "${normalizedOptionKey}" passed to enableSassLoader(). Valid keys are ${Object.keys(this.sassOptions).join(', ')}`);
}
this.sassOptions[normalizedOptionKey] = options[optionKey];
}
}
enableLessLoader(lessLoaderOptionsCallback = () => {}) {
this.useLessLoader = true;
if (typeof lessLoaderOptionsCallback !== 'function') {
throw new Error('Argument 1 to enableLessLoader() must be a callback function.');
}
this.lessLoaderOptionsCallback = lessLoaderOptionsCallback;
}
enableStylusLoader(stylusLoaderOptionsCallback = () => {}) {
this.useStylusLoader = true;
if (typeof stylusLoaderOptionsCallback !== 'function') {
throw new Error('Argument 1 to enableStylusLoader() must be a callback function.');
}
this.stylusLoaderOptionsCallback = stylusLoaderOptionsCallback;
}
enableReactPreset() {
this.useReact = true;
}
enablePreactPreset(options = {}) {
this.usePreact = true;
for (const optionKey of Object.keys(options)) {
if (!(optionKey in this.preactOptions)) {
throw new Error(`Invalid option "${optionKey}" passed to enablePreactPreset(). Valid keys are ${Object.keys(this.preactOptions).join(', ')}`);
}
this.preactOptions[optionKey] = options[optionKey];
}
}
enableTypeScriptLoader(callback = () => {}) {
this.useTypeScriptLoader = true;
if (typeof callback !== 'function') {
throw new Error('Argument 1 to enableTypeScriptLoader() must be a callback function.');
}
this.tsConfigurationCallback = callback;
}
enableForkedTypeScriptTypesChecking(forkedTypeScriptTypesCheckOptionsCallback = () => {}) {
if (typeof forkedTypeScriptTypesCheckOptionsCallback !== 'function') {
throw new Error('Argument 1 to enableForkedTypeScriptTypesChecking() must be a callback function.');
}
this.useForkedTypeScriptTypeChecking = true;
this.forkedTypeScriptTypesCheckOptionsCallback =
forkedTypeScriptTypesCheckOptionsCallback;
}
enableVueLoader(vueLoaderOptionsCallback = () => {}) {
this.useVueLoader = true;
if (typeof vueLoaderOptionsCallback !== 'function') {
throw new Error('Argument 1 to enableVueLoader() must be a callback function.');
}
this.vueLoaderOptionsCallback = vueLoaderOptionsCallback;
}
enableEslintLoader(eslintLoaderOptionsOrCallback = () => {}) {
this.useEslintLoader = true;
if (typeof eslintLoaderOptionsOrCallback === 'function') {
this.eslintLoaderOptionsCallback = eslintLoaderOptionsOrCallback;
return;
}
if (typeof eslintLoaderOptionsOrCallback === 'string') {
this.eslintLoaderOptionsCallback = (options) => {
options.extends = eslintLoaderOptionsOrCallback;
};
return;
}
if (typeof eslintLoaderOptionsOrCallback === 'object') {
this.eslintLoaderOptionsCallback = (options) => {
Object.assign(options, eslintLoaderOptionsOrCallback);
};
return;
}
throw new Error('Argument 1 to enableEslintLoader() must be either a string, object or callback function.');
}
enableBuildNotifications(enabled = true, notifierPluginOptionsCallback = () => {}) {
if (typeof notifierPluginOptionsCallback !== 'function') {
throw new Error('Argument 2 to enableBuildNotifications() must be a callback function.');
}
this.useWebpackNotifier = enabled;
this.notifierPluginOptionsCallback = notifierPluginOptionsCallback;
}
enableHandlebarsLoader(callback = () => {}) {
this.useHandlebarsLoader = true;
if (typeof callback !== 'function') {
throw new Error('Argument 1 to enableHandlebarsLoader() must be a callback function.');
}
this.handlebarsConfigurationCallback = callback;
}
disableImagesLoader() {
this.useImagesLoader = false;
}
disableFontsLoader() {
this.useFontsLoader = false;
}
disableCssExtraction() {
this.extractCss = false;
}
configureFilenames(configuredFilenames = {}) {
if (typeof configuredFilenames !== 'object') {
throw new Error('Argument 1 to configureFilenames() must be an object.');
}
// Check allowed keys
const validKeys = ['js', 'css', 'images', 'fonts'];
for (const key of Object.keys(configuredFilenames)) {
if (validKeys.indexOf(key) === -1) {
throw new Error(`"${key}" is not a valid key for configureFilenames(). Valid keys: ${validKeys.join(', ')}.`);
}
}
if (typeof configuredFilenames.js !== 'undefined' && configuredFilenames.js.includes('[chunkhash')) {
logger.deprecation('Using the [chunkhash] placeholder in any filenames is deprecated: use [contenthash] instead.');
}
this.configuredFilenames = configuredFilenames;
}
configureUrlLoader(urlLoaderOptions = {}) {
if (typeof urlLoaderOptions !== 'object') {
throw new Error('Argument 1 to configureUrlLoader() must be an object.');
}
// Check allowed keys
const validKeys = ['images', 'fonts'];
for (const key of Object.keys(urlLoaderOptions)) {
if (validKeys.indexOf(key) === -1) {
throw new Error(`"${key}" is not a valid key for configureUrlLoader(). Valid keys: ${validKeys.join(', ')}.`);
}
}
this.urlLoaderOptions = urlLoaderOptions;
}
cleanupOutputBeforeBuild(paths = ['**/*'], cleanWebpackPluginOptionsCallback = () => {}) {
if (!Array.isArray(paths)) {
throw new Error('Argument 1 to cleanupOutputBeforeBuild() must be an Array of paths - e.g. [\'**/*\']');
}
if (typeof cleanWebpackPluginOptionsCallback !== 'function') {
throw new Error('Argument 2 to cleanupOutputBeforeBuild() must be a callback function');
}
this.cleanupOutput = true;
this.cleanWebpackPluginPaths = paths;
this.cleanWebpackPluginOptionsCallback = cleanWebpackPluginOptionsCallback;
}
autoProvideVariables(variables) {
// do a few sanity checks, so we can give better user errors
if (typeof variables === 'string' || Array.isArray(variables)) {
throw new Error('Invalid argument passed to autoProvideVariables: you must pass an object map - e.g. { $: "jquery" }');
}
// merge new variables into the object
this.providedVariables = Object.assign(
{},
this.providedVariables,
variables
);
}
autoProvidejQuery() {
this.autoProvideVariables({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
});
}
configureLoaderRule(name, callback) {
logger.warning('Be careful when using Encore.configureLoaderRule(), this is a low-level method that can potentially break Encore and Webpack when not used carefully.');
// Key: alias, Value: existing loader in `this.loaderConfigurationCallbacks`
const aliases = {
js: 'javascript',
ts: 'typescript',
scss: 'sass',
};
if (name in aliases) {
name = aliases[name];
}
if (!(name in this.loaderConfigurationCallbacks)) {
throw new Error(`Loader "${name}" is not configurable. Valid loaders are "${Object.keys(this.loaderConfigurationCallbacks).join('", "')}" and the aliases "${Object.keys(aliases).join('", "')}".`);
}
if (typeof callback !== 'function') {
throw new Error('Argument 2 to configureLoaderRule() must be a callback function.');
}
this.loaderConfigurationCallbacks[name] = callback;
}
enableIntegrityHashes(enabled = true, algorithms = ['sha384']) {
if (!Array.isArray(algorithms)) {
algorithms = [algorithms];
}
const availableHashes = crypto.getHashes();
for (const algorithm of algorithms) {
if (typeof algorithm !== 'string') {
throw new Error('Argument 2 to enableIntegrityHashes() must be a string or an array of strings.');
}
if (!availableHashes.includes(algorithm)) {
throw new Error(`Invalid hash algorithm "${algorithm}" passed to enableIntegrityHashes().`);
}
}
this.integrityAlgorithms = enabled ? algorithms : [];
}
useDevServer() {
return this.runtimeConfig.useDevServer;
}
useDevServerInHttps() {
return this.runtimeConfig.devServerHttps;
}
useHotModuleReplacementPlugin() {
return this.runtimeConfig.useHotModuleReplacement;
}
isProduction() {
return this.runtimeConfig.environment === 'production';
}
isDev() {
return this.runtimeConfig.environment === 'dev';
}
isDevServer() {
return this.isDev() && this.runtimeConfig.useDevServer;
}
}
module.exports = WebpackConfig;