This repository has been archived by the owner on Aug 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
484 lines (458 loc) · 13.1 KB
/
index.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
const webpack = require('webpack')
const webpackMerge = require('webpack-merge')
const { mapValues } = require('lodash')
const ifProd = (prod, notProd) =>
process.env.NODE_ENV === 'production' ? prod : notProd
const baseConfig = () => ({
output: {
filename: `[name]${ifProd('.[chunkhash]', '')}.js`,
chunkFilename: `[name]${ifProd('.[chunkhash]', '')}.js`,
publicPath: '/',
},
})
const merge = (...mergees) => a => webpackMerge(a, ...mergees.filter(x => x))
const dumbMerge = b => a => Object.assign({}, a, b)
const flatten = arr =>
arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])
/**
* Combine multiple webpack parts into a webpack config. A part is either an
* object, which will be merged in to the config, or it is a function that takes
* the config as it is and is expected to return a new version of the config.
* The parts are resolved in the order they are provided. There is a small base
* config that combine starts with that looks like this:
*
* ```js
* {
* output: {
* filename: '[name].[chunkhash].js',
* chunkFilename: '[name].[chunkhash].js',
* publicPath: '/'
* }
* }
* ```
*
* @function combine
* @param {Array<Object|Function>} parts Array of webpack config objects or functions
* @returns {Object} Combined Webpack config object
* @example
* // webpack.config.js
* const parts = require('webpack-parts')
*
* module.exports = parts.combine(
* {
* entry: "app/index.js",
* output: {
* path: "build"
* }
* },
* parts.load.js(),
* parts.load.css(),
* parts.dev.sourceMaps(),
* parts.optimize.minimize()
* )
*/
const combine = (...parts) =>
flatten(parts)
.filter(x => x)
.reduce(
(config, part) =>
typeof part === 'function' ? part(config) : webpackMerge(config, part),
baseConfig()
)
const flow = (...fs) =>
x => flatten(fs).filter(x => x).reduce((acc, f) => f(acc), x)
const inlineCss = ({ include, postcssOptions }) => ({
module: {
rules: [
{
include,
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
options: postcssOptions,
},
],
},
],
},
})
/**
* Use postcss to process css.
*
* @function load.css
* @param {string|Array} [$0.include] [Webpack include
* conditions](https://webpack.js.org/configuration/module/#condition)
* @param {Object} [$0.postcssOptions] [postcss-loader
* options](https://github.com/postcss/postcss-loader#options)
* @param {string} [$0.extractFilename] Path to extract css to using
* `extract-text-webpack-plugin` when
* `NODE_ENV=production`
*/
const css = ({ include, postcssOptions, extractFilename } = {}) => ifProd(
config => {
if (!extractFilename)
return merge(inlineCss({ include, postcssOptions }))(config)
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const extractPlugin = new ExtractTextWebpackPlugin(extractFilename)
return merge({
module: {
rules: [
{
include,
test: /\.css$/,
use: extractPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
options: postcssOptions,
},
],
}),
},
],
},
plugins: [extractPlugin],
})(config)
},
inlineCss({ include, postcssOptions })
)
/**
* Use babel to process js.
*
* @function load.js
* @param {string|Array} [$0.include] [Webpack include
* conditions](https://webpack.js.org/configuration/module/#condition)
* @param {string} [$0.basePath] The base path to which js files will be
* emitted. It's essentially a prefix to
* `fileName` and `chunkFilename`
*/
const js = ({ include, basePath = '' } = {}) => ({
output: {
filename: `${basePath}[name]${ifProd('.[chunkhash]', '')}.js`,
chunkFilename: `${basePath}[name]${ifProd('.[chunkhash]', '')}.js`,
publicPath: '/',
},
module: {
rules: [
{
include,
test: /\.jsx?$/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
})
/**
* Include images via urls.
*
* @function load.images
* @param {string|Array} [$0.include] [Webpack include
* conditions](https://webpack.js.org/configuration/module/#condition)
* @param {Object} [$0.imageOptions] Options to pass to `image-webpack-loader`
* @param {string} [$0.basePath] The base path to which images files will be
* emitted.
* @param {number} [$0.inlineLimitBytes] If set, inline images that are smaller
* than $0.inlineLimitBytes when `NODE_ENV
* === 'production'`
*/
const images = (
{ include, imageOptions, basePath = '', inlineLimitBytes } = {}
) => ({
module: {
rules: [
{
include,
test: /\.(png|jpg|gif|svg)$/,
use: ifProd(
[
inlineLimitBytes
? {
loader: 'url-loader',
options: {
inlineLimitBytes,
name: `${basePath}[name].[hash:8].[ext]`,
},
}
: {
loader: 'file-loader',
options: {
name: `${basePath}[name].[hash:8].[ext]`,
},
},
{
loader: 'image-webpack-loader',
options: imageOptions,
},
],
[
{
loader: 'file-loader',
options: {
name: `${basePath}[name].[ext]`,
},
},
]
),
},
],
},
})
/**
* Extract all used dependencies from `node_modules` into a separate `vendor.js`.
* By default, it will consider all dependencies used by all entry points, but
* you override this by specifying `$0.chunks`.
*
* @function output.vendorNodeModules
* @param {string} [$0.name] Name of vendor chunk
* @param {Array<string>} [$0.chunks] Array of entry chunk names to consider
* when looking for used `node_modules`.
*/
const vendorNodeModules = ({ name = 'vendor', chunks }) => ({
plugins: [
new webpack.optimize.CommonsChunkPlugin({
minChunks(module) {
return module.context && module.context.indexOf('node_modules') !== -1
},
names: [name],
chunks,
}),
],
})
/**
* Make environment variables available via `process.env` while building. The
* variables are copied from the current environment at build time. If you want
* to set environment variables to something other to what they actually are in
* the current environment, use `setEnv`. Makes use of
* `webpack.EnvironmentPlugin`.
*
* @function setup.copyEnv
* @param {Array<string>} vars The names of environment variables to make available.
*/
const copyEnv = vars => ({
plugins: [new webpack.EnvironmentPlugin(vars)],
})
/**
* Make environment variables available via `process.env` while building. The
* variables are set explicitly as specified in `env`. Note that you should not
* `JSON.stringify` the values, that will be done for you. Makes use of
* `webpack.DefinePlugin`
*
* @function setup.setEnv
* @param {Object} env An object whose keys are the names of environment
* variables and whose values are the values to set. These
* should be plain JSON objects.
*/
const setEnv = env => ({
plugins: [
new webpack.DefinePlugin({
'process.env': mapValues(env, value => JSON.stringify(value)),
}),
],
})
const prependToEntry = (entry, file) => {
if (typeof entry === 'string') return [file, entry]
if (Array.isArray(entry)) return [file, ...entry]
return mapValues(entry, subEntry => prependToEntry(subEntry, file))
}
const prependToEachEntry = file => config => dumbMerge({
entry: prependToEntry(config.entry, file),
})(config)
const failIfNotConfigured = (field, name) => config => {
if (!config[field]) {
throw new Error(
`Please ensure that "${field}" is set before using ${name}`
)
}
return config
}
/**
* Use `webpack-bundle-analyzer` to analyze bundle size. Opens a web browser
* with a visual graph of bundled modules and their sizes
*
* @function dev.analyze
*/
const analyze = () => ({
plugins: [
new (require('webpack-bundle-analyzer').BundleAnalyzerPlugin)({
analyzerMode: 'static',
}),
],
})
/**
* Enable hot module reloading when `NODE_ENV !== 'production'`
*
* @function dev.hotModuleReloading
* @param {boolean} [$0.useReactHotLoader] Set to true if you're using
* `react-hot-loader`. Adds `react-hot-loader/patch` to each
* entry.
* @param {boolean} [$0.useWebpackHotMiddleware] Set to true if you're using
* `webpack-hot-middleware`. Adds
* `webpack-hot-middleware/client` to each entry.
* @param {boolean} [$0.webpackDevServerUrl] Set to url such as
* `http://localhost:3000` if you're using
* `webpack-dev-server`. Adds `webpack-dev-server/client` and
* `webpack/hot/only-dev-server` to each entry. Should not be
* used with `useWebpackHotMiddleware`.
*/
const hotModuleReloading = (
{
useReactHotLoader,
useWebpackHotMiddleware,
webpackDevServerUrl,
} = {}
) => ifProd(
null,
flow(
failIfNotConfigured('entry', 'hotModuleReloading'),
useWebpackHotMiddleware &&
prependToEachEntry('webpack-hot-middleware/client'),
webpackDevServerUrl && prependToEachEntry('webpack/hot/only-dev-server'),
webpackDevServerUrl &&
prependToEachEntry(`webpack-dev-server/client?${webpackDevServerUrl}`),
useReactHotLoader && prependToEachEntry('react-hot-loader/patch'),
merge({
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
})
)
)
/**
* Enable source maps. Uses different options depending on NODE_ENV.
*
* @function dev.sourceMaps
* @param {string} $0.development devtool to use in development. Defaults to
* `cheap-module-source-map`
* @param {string} $0.production devtool to use in production. Defaults to
* `source-map`
*/
const sourceMaps = (
{
development = 'cheap-module-source-map',
production = 'source-map',
} = {}
) => ({ devtool: ifProd(production, development) })
/**
* Force to a single version of lodash across all dependencies. Lodash is big
* and we don't want to include it or its bits more than once. This is probably
* safe as long as there are no mixed major versions and the most recent version
* of lodash is the one forced.
*
* @function optimize.forceSingleLodash
* @param {string} lodashPath Absolute path to lodash module
* @example
* parts.optimize.forceSingleLodash(require.resolve('lodash'))
*/
const forceSingleLodash = lodashPath => ({
resolve: {
alias: {
lodash: lodashPath,
'lodash-es': lodashPath,
},
},
})
/**
* Minimize javascript code using uglify and configure all other loaders to
* minimize and disable debug if `NODE_ENV === 'production'`.
*
* @function optimize.minimize
*/
const minimize = () => ifProd({
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true, // React doesn't support IE8
warnings: false,
},
mangle: {
screw_ie8: true,
},
output: {
comments: false,
screw_ie8: true,
},
sourceMap: true,
}),
],
})
/**
* Do not include any of moment's locales. If we don't do this, they are all
* included and add 23kb min+gzip. You probably shouldn't use this if you need
* to support other locales.
*
* @function optimize.removeMomentLocales
*/
const removeMomentLocales = () => ({
plugins: [
new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^no-locales$/),
],
})
/**
* Enable progress bar when building at the command line.
*
* @function ui.progressBar
*/
const progressBar = () => ({
plugins: [new (require('progress-bar-webpack-plugin'))()],
})
module.exports = {
combine,
ifProd,
flow,
merge,
dev: {
hotModuleReloading,
sourceMaps,
analyze,
},
load: {
css,
images,
js,
},
optimize: {
forceSingleLodash,
minimize,
removeMomentLocales,
},
output: {
vendorNodeModules,
},
setup: {
copyEnv,
setEnv,
},
ui: {
progressBar,
},
}