-
Notifications
You must be signed in to change notification settings - Fork 331
/
createWebpackConfig.js
670 lines (616 loc) · 21.1 KB
/
createWebpackConfig.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
import path from 'path'
import autoprefixer from 'autoprefixer'
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin'
import {red} from 'chalk'
import CopyPlugin from 'copy-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlPlugin from 'html-webpack-plugin'
import NpmInstallPlugin from 'npm-install-webpack-plugin'
import qs from 'qs'
import webpack, {optimize} from 'webpack'
import failPlugin from 'webpack-fail-plugin'
import Md5HashPlugin from 'webpack-md5-hash'
import merge from 'webpack-merge'
import HashedModuleIdsPlugin from '../vendor/HashedModuleIdsPlugin'
import createBabelConfig from './createBabelConfig'
import debug from './debug'
import {deepToString, endsWith, typeOf} from './utils'
import BuildStatusPlugin from './WebpackBuildStatusPlugin'
// Top-level property names reserved for webpack config
// From http://webpack.github.io/docs/configuration.html
const WEBPACK_RESERVED = 'context entry output module resolve resolveLoader externals target bail profile cache watch watchOptions debug devtool devServer node amd loader recordsPath recordsInputPath recordsOutputPath plugins'.split(' ')
/**
* Create a loader string from a list of {loader, query} objects.
*/
export let combineLoaders = loaders =>
loaders.map(loader => {
let query = qs.stringify(loader.query, {arrayFormat: 'brackets'})
return `${loader.loader}${query && `?${query}`}`
}).join('!')
/**
* Merge webpack loader config ({test, loader, query, include, exclude}) objects.
*/
export function mergeLoaderConfig(defaultConfig = {}, buildConfig = {}, userConfig = {}) {
// Don't include a 'config' object if the user provided one - this will be
// configured at the top level instead.
let {config, ...userLoaderConfig} = userConfig // eslint-disable-line no-unused-vars
let loader = merge(defaultConfig, buildConfig, userLoaderConfig)
if (loader.query && Object.keys(loader.query).length === 0) {
delete loader.query
}
return loader
}
/**
* Create a function which configures a loader identified by a unique id, with
* the option to override defaults with build-specific and user config.
*/
export let loaderConfigFactory = (buildConfig, userConfig) =>
(id, defaultConfig) => {
if (id) {
return {id, ...mergeLoaderConfig(defaultConfig, buildConfig[id], userConfig[id])}
}
return defaultConfig
}
/**
* Create a function which applies a prefix to a given name when a prefix is
* given, unless the prefix ends with a name, in which case the prefix itself is
* returned.
* The latter rule is to allow loaders created for CSS preprocessor plugins to
* be given unique ids for user configuration without duplicating the name of
* the loader.
* e.g.: styleLoaderName('sass')('css') => 'sass-css'
* styleLoaderName('sass')('sass') => 'sass' (as opposed to 'sass-sass')
*/
export let styleLoaderName = (prefix) =>
(name) => {
if (prefix && endsWith(prefix, name)) {
return prefix
}
return prefix ? `${prefix}-${name}` : name
}
/**
* Create a default style-handling pipeline for either a static build (default)
* or a server build.
*/
export function createStyleLoader(loader, server, {
preprocessor = null,
prefix = null,
} = {}) {
let name = styleLoaderName(prefix)
let loaders = [
loader(name('css'), {
loader: require.resolve('css-loader'),
query: {
// Prevent cssnano from using Autoprefixer to remove prefixes
autoprefixer: false,
// Apply postcss-loader to @imports
importLoaders: 1,
},
}),
loader(name('postcss'), {
loader: require.resolve('postcss-loader'),
query: {
pack: prefix,
},
})
]
if (preprocessor) {
loaders.push(loader(name(preprocessor.id), preprocessor.config))
}
if (server) {
loaders.unshift(
loader(name('style'), {
loader: require.resolve('style-loader'),
})
)
return combineLoaders(loaders)
}
else {
return ExtractTextPlugin.extract(
require.resolve('style-loader'),
combineLoaders(loaders)
)
}
}
/**
* Final webpack loader config consists of:
* - the default set of loaders created in this function, with build and user
* config tweaks based on loader id.
* - extra loaders defined in build config, with user config tweaks based
* on loader id.
* - extra loaders created for CSS preprocessor plugins, with user config
* tweaks based on loader id.
* - extra loaders defined in user config.
*/
export function createLoaders(server, buildConfig = {}, userConfig = {}, pluginConfig = {}) {
let loader = loaderConfigFactory(buildConfig, userConfig)
// Filename pattern for file-loader and url-loader
let name = process.env.NODE_ENV === 'production' ? '[name].[hash:8].[ext]' : '[name].[ext]'
let loaders = [
loader('babel', {
test: /\.js$/,
loader: require.resolve('babel-loader'),
exclude: /node_modules/,
query: {
// Don't look for .babelrc files
babelrc: false,
// Cache transformations to the filesystem (in default OS temp dir)
cacheDirectory: true,
}
}),
loader('css-pipeline', {
test: /\.css$/,
loader: createStyleLoader(loader, server),
exclude: /node_modules/,
}),
loader('vendor-css-pipeline', {
test: /\.css$/,
loader: createStyleLoader(loader, server, {
prefix: 'vendor',
}),
include: /node_modules/,
}),
loader('graphics', {
test: /\.(gif|png|svg)$/,
loader: require.resolve('url-loader'),
query: {
name,
},
}),
loader('jpeg', {
test: /\.jpe?g$/,
loader: require.resolve('file-loader'),
query: {
name,
},
}),
loader('fonts', {
test: /\.(otf|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: require.resolve('url-loader'),
query: {
name,
},
}),
loader('eot', {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: require.resolve('file-loader'),
query: {
name,
},
}),
loader('json', {
test: /\.json$/,
loader: require.resolve('json-loader'),
}),
// Extra loaders from build config, still configurable via user config when
// the loaders specify an id.
...createExtraLoaders(buildConfig.extra, userConfig),
]
if (pluginConfig.cssPreprocessors) {
Object.keys(pluginConfig.cssPreprocessors).forEach(id => {
let {test, ...config} = pluginConfig.cssPreprocessors[id]
loaders.push(
loader(`${id}-pipeline`, {
test,
loader: createStyleLoader(loader, server, {
prefix: id,
preprocessor: {id, config},
}),
exclude: /node_modules/
})
)
loaders.push(
loader(`vendor-${id}-pipeline`, {
test,
loader: createStyleLoader(loader, server, {
prefix: `vendor-${id}`,
preprocessor: {id, config},
}),
include: /node_modules/
})
)
})
}
return loaders
}
/**
* Create loaders from loader definitions which may include an id attribute for
* user customisation. It's assumed these are being created from build config.
*/
export function createExtraLoaders(extraLoaders = [], userConfig = {}) {
let loader = loaderConfigFactory({}, userConfig)
return extraLoaders.map(extraLoader => {
let {id, ...loaderConfig} = extraLoader
return loader(id, loaderConfig)
})
}
/**
* Plugin for HtmlPlugin which inlines content for an extracted Webpack
* manifest into the HTML page in a <script> tag before other emitted asssets
* are injected by HtmlPlugin itself.
*/
function injectManifestPlugin() {
this.plugin('compilation', (compilation) => {
compilation.plugin('html-webpack-plugin-before-html-processing', (data, cb) => {
Object.keys(compilation.assets).forEach(key => {
if (key.indexOf('manifest.') !== 0) return
let {children} = compilation.assets[key]
if (children && children[0]) {
data.html = data.html.replace(
'</body>',
`<script>${children[0]._value}</script></body>`
)
// Remove the manifest from HtmlPlugin's assets to
// prevent a <script> tag being created for it.
var manifestIndex = data.assets.js.indexOf(data.assets.publicPath + key)
data.assets.js.splice(manifestIndex, 1)
delete data.assets.chunks.manifest
}
// Prevent manifest .js and .js.map files being emitted
delete compilation.assets[key]
})
cb()
})
})
}
function getCopyPluginArgs(buildConfig, userConfig) {
let patterns = []
let options = {}
if (buildConfig) {
patterns = patterns.concat(buildConfig)
}
if (userConfig) {
patterns = patterns.concat(userConfig.patterns || [])
options = userConfig.options || {}
}
return [patterns, options]
}
/**
* Final webpack plugin config consists of:
* - the default set of plugins created by this function based on whether or not
* a server build is being configured, whether or not the build is for an
* app (for which HTML will be generated), plus environment variables.
* - extra plugins managed by this function, whose inclusion is triggered by
* build config, which provides default configuration for them which can be
* tweaked by user plugin config when appropriate.
* - any extra plugins defined in build and user config (extra user plugins are
* not handled here, but by the final merge of webpack.extra config).
*/
export function createPlugins(server, buildConfig = {}, userConfig = {}) {
let production = process.env.NODE_ENV === 'production'
let plugins = [
// Enforce case-sensitive import paths
new CaseSensitivePathsPlugin(),
]
// Fail the build if there are compilation errors when running on CI
if (process.env.CONTINUOUS_INTEGRATION === 'true') {
plugins.push(failPlugin)
}
if (server) {
// HMR isn't enabled when running tests
if (!server.test) {
let url = `http://${server.host || 'localhost'}:${server.port}/`
plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new BuildStatusPlugin({
mode: 'serve',
message: `The app is running at ${url}`
}),
)
}
else {
plugins.push(new BuildStatusPlugin({mode: 'test'}))
}
// Use paths as names when serving
plugins.push(new webpack.NamedModulesPlugin())
}
else {
plugins.push(new BuildStatusPlugin({mode: 'build'}))
}
plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
...buildConfig.define,
...userConfig.define,
}),
)
// If we're not serving, we're creating a static build
if (!server) {
// Extract CSS into files
let cssFilename = production ? `[name].[contenthash:8].css` : '[name].css'
plugins.push(new ExtractTextPlugin(cssFilename, {
...userConfig.extractText,
}))
// Move modules imported from node_modules/ into a vendor chunk when enabled
if (userConfig.vendorBundle !== false && buildConfig.vendorChunkName) {
plugins.push(new optimize.CommonsChunkPlugin({
name: buildConfig.vendorChunkName,
minChunks(module, count) {
return (
module.resource &&
module.resource.indexOf('node_modules') !== -1
)
}
}))
}
// If we're generating an HTML file, we must be building a webapp, so
// configure deterministic hashing for long-term caching.
if (buildConfig.html) {
plugins.push(
// Generate stable module ids by hashing module paths instead of
// assigning integers.
new HashedModuleIdsPlugin(),
// The MD5 Hash plugin seems to make [chunkhash] for .js files behave
// like [contenthash] does for extracted .css files, which is essential
// for deterministic hashing.
new Md5HashPlugin(),
// The Webpack manifest is normally folded into the last chunk, changing
// its hash - prevent this by extracting the manifest into its own
// chunk - also essential for deterministic hashing.
new optimize.CommonsChunkPlugin({name: 'manifest'}),
// Inject the Webpack manifest into the generated HTML as a <script>
injectManifestPlugin,
)
}
}
if (production) {
plugins.push(
new optimize.DedupePlugin(),
new optimize.UglifyJsPlugin(merge({
compress: {
screw_ie8: true,
warnings: false,
},
mangle: {
screw_ie8: true,
},
output: {
comments: false,
screw_ie8: true,
},
}, userConfig.uglify)),
)
}
if (buildConfig.html) {
plugins.push(
// Generate the app's HTML file
new HtmlPlugin({
chunksSortMode: 'dependency',
template: path.join(__dirname, '../templates/webpack-template.html'),
...buildConfig.html,
...userConfig.html,
}),
)
}
if (buildConfig.copy) {
plugins.push(
new CopyPlugin(...getCopyPluginArgs(buildConfig.copy, userConfig.copy))
)
}
if (buildConfig.install) {
plugins.push(new NpmInstallPlugin({
...buildConfig.install,
...userConfig.install,
}))
}
if (buildConfig.banner) {
plugins.push(new webpack.BannerPlugin(buildConfig.banner))
}
if (buildConfig.extra) {
plugins = plugins.concat(buildConfig.extra)
}
return plugins
}
/**
* Extract top-level loader configuration provided by the user.
*/
export function getTopLevelLoaderConfig(userLoaderConfig, cssPreprocessors = {}) {
if (!userLoaderConfig || Object.keys(userLoaderConfig).length === 0) {
return {}
}
let topLevelLoaderConfig = {}
Object.keys(userLoaderConfig).forEach(loaderId => {
let loaderConfig = userLoaderConfig[loaderId]
if (!('config' in loaderConfig)) return
// Determine the proeprty to set top level loader config under
let configPropertyName
// Trust the user to specify their own config key for loaders with support
if (loaderConfig.query && 'config' in loaderConfig.query) {
configPropertyName = loaderConfig.query.config
}
else {
// Otherwise, determine the correct config key
let id = loaderId.replace(/^vendor-/, '')
if (id in cssPreprocessors) {
if (!cssPreprocessors[id].defaultConfig) {
throw new Error(`The ${id} CSS preprocessor loader doesn't support a default top-level config object.`)
}
configPropertyName = cssPreprocessors[id].defaultConfig
}
else if (id === 'babel') {
configPropertyName = 'babel'
}
else {
throw new Error(`The ${id} loader doesn't appear to support a default top-level config object.`)
}
}
if (WEBPACK_RESERVED.indexOf(configPropertyName) !== -1) {
throw new Error(
`User config for the ${loaderId} loader cannot be set in ${configPropertyName} - this is reserved for use by Webpack.`
)
}
else if (configPropertyName in topLevelLoaderConfig) {
throw new Error(
`User config for the ${loaderId} loader cannot be set in ${configPropertyName} - this has already been used.`
)
}
topLevelLoaderConfig[configPropertyName] = loaderConfig.config
})
return topLevelLoaderConfig
}
/**
* Create top-level PostCSS plugin config for each style pipeline.
*/
export function createPostCSSConfig(userWebpackConfig, cssPreprocessors = {}) {
// postcss-loader throws an error if a pack name is provided but isn't
// configured, so we need to set the default PostCSS plugins for every single
// style pipeline.
let postcss = {
defaults: createDefaultPostCSSPlugins(userWebpackConfig),
vendor: createDefaultPostCSSPlugins(userWebpackConfig),
}
Object.keys(cssPreprocessors).forEach(id => {
postcss[id] = createDefaultPostCSSPlugins(userWebpackConfig)
postcss[`vendor-${id}`] = createDefaultPostCSSPlugins(userWebpackConfig)
})
// Any PostCSS plugins provided by the user will completely overwrite defaults
return {...postcss, ...userWebpackConfig.postcss}
}
function createDefaultPostCSSPlugins(userWebpackConfig) {
return [autoprefixer(userWebpackConfig.autoprefixer || {})]
}
export const COMPAT_CONFIGS = {
enzyme: {
externals: {
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true,
}
},
'json-schema': {
module: {
noParse: [/node_modules[/\\]json-schema[/\\]lib[/\\]validate\.js/],
},
},
moment({locales}) {
if (!Array.isArray(locales)) {
console.error(red("nwb: webpack.compat.moment config must provide a 'locales' Array"))
return
}
return {
plugins: [
new webpack.ContextReplacementPlugin(
/moment[/\\]locale$/,
new RegExp(`^\\.\\/(${locales.join('|')})$`)
)
]
}
},
sinon: {
module: {
noParse: [/[/\\]sinon\.js/],
},
resolve: {
alias: {
sinon: 'sinon/pkg/sinon',
},
},
},
}
/**
* Create a chunk of webpack config containing compatibility tweaks for
* libraries which are known to cause issues, to be merged into the generated
* config.
* Returns null if there's nothing to merge based on user config.
*/
export function getCompatConfig(userCompatConfig = {}) {
let configs = []
Object.keys(userCompatConfig).map(lib => {
if (!userCompatConfig[lib]) return
if (!COMPAT_CONFIGS.hasOwnProperty(lib)) {
console.error(red(`nwb: unknown property in webpack.compat config: ${lib}`))
return
}
let compatConfig = COMPAT_CONFIGS[lib]
if (typeOf(compatConfig) === 'function') {
compatConfig = compatConfig(userCompatConfig[lib])
if (!compatConfig) return
}
configs.push(compatConfig)
})
return configs.length > 0 ? merge(...configs) : null
}
/**
* Add default polyfills to the head of the entry array.
*/
function addPolyfillsToEntry(entry) {
let polyfills = require.resolve('../polyfills')
if (typeOf(entry) === 'array') {
entry.unshift(polyfills)
}
else {
// Assumption: there will only be one entry point, naming the entry chunk
entry[Object.keys(entry)[0]].unshift(polyfills)
}
}
/**
* Create a webpack config with a curated set of default loaders suitable for
* creating a static build (default) or serving an app with hot reloading.
*/
export default function createWebpackConfig(buildConfig, nwbPluginConfig = {}, userConfig = {}) {
debug('createWebpackConfig buildConfig: %s', deepToString(buildConfig))
// Final webpack config is primarily driven by build configuration for the nwb
// command being run. Each command configures a default, working webpack
// configuration for the task it needs to perform.
let {
// These build config items are used to create chunks of webpack config,
// rather than being included as-is.
babel: buildBabelConfig = {},
entry,
loaders: buildLoaderConfig = {},
polyfill: buildPolyfill,
plugins: buildPluginConfig = {},
resolve: buildResolveConfig = {},
server = false,
// Any other build config provided is merged directly into the final webpack
// config to provide the rest of the default config.
...otherBuildConfig
} = buildConfig
let userWebpackConfig = userConfig.webpack || {}
let userResolveConfig = {}
if (userWebpackConfig.aliases) {
userResolveConfig.alias = userWebpackConfig.aliases
}
// Generate config for babel-loader and set it as loader config for the build
buildLoaderConfig.babel = {query: createBabelConfig(buildBabelConfig, userConfig.babel)}
let webpackConfig = {
module: {
loaders: createLoaders(server, buildLoaderConfig, userWebpackConfig.loaders, nwbPluginConfig)
},
plugins: createPlugins(server, buildPluginConfig, userWebpackConfig),
resolve: merge({
extensions: ['', '.js', '.json'],
// Fall back to resolving runtime dependencies from nwb's dependencies,
// e.g. for babel-runtime when using the transform-runtime plugin.
fallback: path.join(__dirname, '../node_modules'),
}, buildResolveConfig, userResolveConfig),
postcss: createPostCSSConfig(userWebpackConfig, nwbPluginConfig.cssPreprocessors),
...otherBuildConfig,
// Top level loader config can be supplied via user "loaders" config, so we
// detect, extract and where possible validate it before merging it into the
// final webpack config object.
...getTopLevelLoaderConfig(userWebpackConfig.loaders, nwbPluginConfig.cssPreprocessors),
}
if (entry) {
// Add default polyfills to the entry chunk unless configured not to
if (buildPolyfill !== false && userConfig.polyfill !== false) {
addPolyfillsToEntry(entry)
}
webpackConfig.entry = entry
}
// Create and merge compatibility configuration into the generated config if
// specified.
if (userWebpackConfig.compat) {
let compatConfig = getCompatConfig(userWebpackConfig.compat)
if (compatConfig) {
webpackConfig = merge(webpackConfig, compatConfig)
}
}
// Any extra user webpack config is merged into the generated config to give
// them even more control.
if (userWebpackConfig.extra) {
webpackConfig = merge(webpackConfig, userWebpackConfig.extra)
}
return webpackConfig
}