-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathWebpackConfig.js
500 lines (397 loc) · 17.1 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
/*
* This file is part of the Symfony Webpack Encore package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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 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.imagesPublicPath = null;
this.fontsPublicPath = null;
this.manifestKeyPrefix = null;
this.sharedCommonsEntryName = null;
this.providedVariables = {};
this.configuredFilenames = {};
// Features/Loaders flags
this.useVersioning = false;
this.useSourceMaps = false;
this.cleanupOutput = false;
this.useImagesLoader = true;
this.useFontsLoader = true;
this.usePostCssLoader = false;
this.useLessLoader = false;
this.useSassLoader = false;
this.useReact = false;
this.usePreact = false;
this.useVueLoader = false;
this.useTypeScriptLoader = false;
this.useForkedTypeScriptTypeChecking = false;
// Features/Loaders options
this.sassOptions = {
resolveUrlLoader: true
};
this.preactOptions = {
preactCompat: false
};
// Features/Loaders options callbacks
this.postCssLoaderOptionsCallback = () => {};
this.sassLoaderOptionsCallback = () => {};
this.lessLoaderOptionsCallback = () => {};
this.babelConfigurationCallback = () => {};
this.vueLoaderOptionsCallback = () => {};
this.tsConfigurationCallback = () => {};
// Plugins options
this.cleanWebpackPluginPaths = ['**/*'];
// Plugins callbacks
this.cleanWebpackPluginOptionsCallback = () => {};
this.definePluginOptionsCallback = () => {};
this.extractTextPluginOptionsCallback = () => {};
this.forkedTypeScriptTypesCheckOptionsCallback = () => {};
this.friendlyErrorsPluginOptionsCallback = () => {};
this.loaderOptionsPluginOptionsCallback = () => {};
this.manifestPluginOptionsCallback = () => {};
this.uglifyJsPluginOptionsCallback = () => {};
}
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)) {
// for safety, we won't recursively create directories
// this might be a sign that the user has specified
// an incorrect path
if (!fs.existsSync(path.dirname(outputPath))) {
throw new Error(`outputPath directory does not exist: ${outputPath}. Please check the path you're passing to setOutputPath() or create this directory`);
}
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 not let the user make
// a mistake (and we can always change this later).
throw new Error('The value passed to setPublicPath() must start with "/" or be a full URL (http://...)');
}
// guarantee a single trailing slash
publicPath = publicPath.replace(/\/$/,'');
publicPath = publicPath + '/';
this.publicPath = publicPath;
}
setFontsPublicPath(publicPath) {
// guarantee a single trailing slash
publicPath = publicPath.replace(/\/$/,'');
publicPath = publicPath + '/';
this.fontsPublicPath = publicPath;
}
setImagesPublicPath(publicPath) {
// guarantee a single trailing slash
publicPath = publicPath.replace(/\/$/,'');
publicPath = publicPath + '/';
this.imagesPublicPath = 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;
}
configureExtractTextPlugin(extractTextPluginOptionsCallback = () => {}) {
if (typeof extractTextPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureExtractTextPlugin() must be a callback function');
}
this.extractTextPluginOptionsCallback = extractTextPluginOptionsCallback;
}
configureFriendlyErrorsPlugin(friendlyErrorsPluginOptionsCallback = () => {}) {
if (typeof friendlyErrorsPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureFriendlyErrorsPlugin() must be a callback function');
}
this.friendlyErrorsPluginOptionsCallback = friendlyErrorsPluginOptionsCallback;
}
configureLoaderOptionsPlugin(loaderOptionsPluginOptionsCallback = () => {}) {
if (typeof loaderOptionsPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureLoaderOptionsPlugin() must be a callback function');
}
this.loaderOptionsPluginOptionsCallback = loaderOptionsPluginOptionsCallback;
}
configureManifestPlugin(manifestPluginOptionsCallback = () => {}) {
if (typeof manifestPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureManifestPlugin() must be a callback function');
}
this.manifestPluginOptionsCallback = manifestPluginOptionsCallback;
}
configureUglifyJsPlugin(uglifyJsPluginOptionsCallback = () => {}) {
if (typeof uglifyJsPluginOptionsCallback !== 'function') {
throw new Error('Argument 1 to configureUglifyJsPlugin() must be a callback function');
}
this.uglifyJsPluginOptionsCallback = uglifyJsPluginOptionsCallback;
}
/**
* 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;
}
getFontsPublicPath() {
// if we're using webpack-dev-server, use it & add the publicPath
if (this.useDevServer()) {
// avoid 2 middle slashes
return this.runtimeConfig.devServerUrl.replace(/\/$/,'') + this.publicPath;
} else {
return this.fontsPublicPath;
}
}
getImagesPublicPath() {
// if we're using webpack-dev-server, use it & add the publicPath
if (this.useDevServer()) {
// avoid 2 middle slashes
return this.runtimeConfig.devServerUrl.replace(/\/$/,'') + this.publicPath;
} else {
return this.imagesPublicPath;
}
}
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) {
this.plugins.push(plugin);
}
addLoader(loader) {
this.loaders.push(loader);
}
enableVersioning(enabled = true) {
this.useVersioning = enabled;
}
enableSourceMaps(enabled = true) {
this.useSourceMaps = enabled;
}
configureBabel(callback) {
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;
}
createSharedEntry(name, files) {
// 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.');
}
this.sharedCommonsEntryName = name;
this.addEntry(name, files);
}
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;
}
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;
}
disableImagesLoader() {
this.useImagesLoader = false;
}
disableFontsLoader() {
this.useFontsLoader = 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(', ')}.`);
}
}
this.configuredFilenames = configuredFilenames;
}
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',
});
}
useDevServer() {
return this.runtimeConfig.useDevServer;
}
useDevServerInHttps() {
return this.runtimeConfig.devServerHttps;
}
useHotModuleReplacementPlugin() {
return this.runtimeConfig.useHotModuleReplacement;
}
isProduction() {
return this.runtimeConfig.environment === 'production';
}
}
module.exports = WebpackConfig;