This repository has been archived by the owner on Nov 15, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ConfigFactory.js
979 lines (822 loc) · 30.9 KB
/
ConfigFactory.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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
import { statSync } from "fs"
import path from "path"
import webpack from "webpack"
import AssetsPlugin from "assets-webpack-plugin"
import builtinModules from "builtin-modules"
import ExtractTextPlugin from "extract-text-webpack-plugin"
import CodeSplitWebpackPlugin from "code-split-component/webpack"
import BabiliPlugin from "babili-webpack-plugin"
import HardSourceWebpackPlugin from "hard-source-webpack-plugin"
import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer"
import ChunkManifestPlugin from "chunk-manifest-webpack-plugin"
import OfflinePlugin from "offline-plugin"
import dotenv from "dotenv"
// Using more modern approach of hashing than "webpack-md5-hash". Somehow the SHA256 version
// ("webpack-sha-hash") does not correctly work based (produces different hashes for same content).
// This is basically a replacement of md5 with the loader-utils implementation which also supports
// shorter generated hashes based on base62 encoding instead of hex.
import WebpackDigestHash from "./ChunkHash"
import esModules from "./Modules"
import getPostCSSConfig from "./PostCSSConfig"
import { startsWith, includes } from "lodash"
const builtInSet = new Set(builtinModules)
// - "intl" is included in one block with complete data. No reason for bundle everything here.
// - "react-intl" for the same reason as "intl" - contains a ton of locale data
// - "mime-db" database for working with mime types. Naturally pretty large stuff.
// - "helmet" uses some look with require which are not solvable with webpack
// - "express" also uses some dynamic requires
// - "encoding" uses dynamic iconv loading
// - "node-pre-gyp" native code module helper
// - "iltorb" brotli compression wrapper for NodeJS
// - "node-zopfli" native Zopfli implementation
const problematicCommonJS = new Set([ "intl", "react-intl", "mime-db", "helmet", "express", "encoding", "node-pre-gyp", "iltorb", "node-zopfli" ])
const CWD = process.cwd()
// @see https://github.com/motdotla/dotenv
dotenv.config()
class VerboseProgressPlugin {
constructor(options) {
this.options = options
this.cwd = process.cwd()
}
apply(compiler)
{
compiler.plugin("compilation", function(compilation)
{
if (compilation.compiler.isChild())
return
var moduleCounter = 0
var activeModules = {}
var slicePathBy = process.cwd().length + 1
function now(time) {
return process.hrtime(time)
}
function moduleStart(module) {
var ident = module.identifier()
if (ident) {
if (startsWith(ident, "ignored") || startsWith(ident, "external")) {
return
}
moduleCounter++
if (moduleCounter % 100 === 0) {
console.log("- Building module #" + moduleCounter)
}
activeModules[ident] = now()
}
}
function moduleDone(module) {
var ident = module.identifier()
if (ident) {
var entry = activeModules[ident];
if (entry == null) {
return
}
var runtime = Math.round(now(entry)[1] / 1000000)
if (includes(ident, "!")) {
var splits = ident.split("!")
ident = splits.pop()
}
var relative = ident.slice(slicePathBy)
// console.log(`Module ${relative} in ${runtime}ms`)
if (splits) {
splits = null
}
}
}
compilation.plugin("build-module", moduleStart)
compilation.plugin("failed-module", moduleDone)
compilation.plugin("succeed-module", moduleDone)
function log(title) {
return function() {
console.log("- " + title)
}
}
compilation.plugin("seal", function() {
console.log("- Sealing " + moduleCounter + " modules...")
})
compilation.plugin("optimize", log("Optimizing modules/chunks/tree..."))
/*
compilation.plugin("optimize-modules-basic", log("Basic module optimization"))
compilation.plugin("optimize-modules", log("Module optimization"))
compilation.plugin("optimize-modules-advanced", log("Advanced module optimization"))
compilation.plugin("optimize-chunks-basic", log("Basic chunk optimization"))
compilation.plugin("optimize-chunks", log("Chunk optimization"))
compilation.plugin("optimize-chunks-advanced", log("Advanced chunk optimization"))
compilation.plugin("optimize-tree", function(chunks, modules, callback) {
console.log("- Module and chunk tree optimization")
callback()
})
compilation.plugin("revive-modules", log("Module reviving"))
compilation.plugin("optimize-module-order", log("Module order optimization"))
compilation.plugin("optimize-module-ids", log("Module id optimization"))
compilation.plugin("revive-chunks", log("Chunk reviving"))
compilation.plugin("optimize-chunk-order", log("Chunk order optimization"))
compilation.plugin("optimize-chunk-ids", log("Chunk id optimization"))
compilation.plugin("before-hash", log("Hashing"))
compilation.plugin("before-module-assets", log("Module assets processing"))
compilation.plugin("before-chunk-assets", log("Chunk assets processing"))
compilation.plugin("additional-chunk-assets", log("Additional chunk assets processing"))
compilation.plugin("record", log("Recording"))
compilation.plugin("additional-assets", function(callback) {
console.log("- Additional asset processing")
callback()
})
*/
compilation.plugin("optimize-chunk-assets", function(chunks, callback) {
console.log("- Optimizing assets...")
callback()
})
/*
compilation.plugin("optimize-assets", function(assets, callback) {
console.log("- Optimizing assets...")
callback()
})
*/
})
compiler.plugin("emit", function(compilation, callback) {
console.log("- Emitting output files...")
callback()
})
}
}
function removeEmpty(array) {
return array.filter((entry) => Boolean(entry))
}
function removeEmptyKeys(obj)
{
var copy = {}
for (var key in obj)
{
if (!(obj[key] == null || obj[key].length === 0))
copy[key] = obj[key]
}
return copy
}
function ifElse(condition) {
return (then, otherwise) => (condition ? then : otherwise)
}
function merge()
{
const funcArgs = Array.prototype.slice.call(arguments) // eslint-disable-line prefer-rest-params
return Object.assign.apply(
null,
removeEmpty([{}].concat(funcArgs))
)
}
function isLoaderSpecificFile(request) {
return Boolean(/\.(eot|woff|woff2|ttf|otf|svg|png|jpg|jpeg|gif|webp|webm|ico|mp4|mp3|ogg|html|pdf|swf|css|scss|sass|sss|less)$/.exec(request))
}
function ifIsFile(filePath) {
try {
return statSync(filePath).isFile() ? filePath : ""
} catch (err) {
// empty
}
return ""
}
function getJsLoader({ isNode, isWeb, isProd, isDev })
{
const nodeBabel = isNode ? {
// Don't try to find .babelrc because we want to force this configuration.
babelrc: false,
// Faster transpiling for minor loose in formatting
compact: true,
// Keep origin information alive
sourceMaps: true,
// Nobody needs the original comments when having source maps
comments: false,
presets:
[
// Exponentiation
"babel-preset-es2016",
// Async to generators + trailing function commas
"babel-preset-es2017",
// JSX, Flow
"babel-preset-react"
],
plugins:
[
// Transpile Markdown into React components. Super smart.
"markdown-in-js/babel",
// Optimization for lodash imports.
// Auto cherry-picking es2015 imports from path imports.
"lodash",
// Keep transforming template literals as it keeps code smaller for the client
// (removes multi line formatting which is allowed for literals)
// This is interesting for all es2015 outputs... e.g.
// later for a client build for modern builds, too
"transform-es2015-template-literals",
// class { handleClick = () => { } }
// https://github.com/tc39/proposal-class-public-fields
"transform-class-properties",
// { ...todo, completed: true }
[ "transform-object-rest-spread", { useBuiltIns: true }],
// Polyfills the runtime needed
[ "transform-runtime", { regenerator: false }],
// Code Splitting by Routes
[
"code-split-component/babel", {
disabled: isDev,
mode: "server"
}
]
]
} : null
const webBabel = isWeb ? {
// Don't try to find .babelrc because we want to force this configuration.
babelrc: false,
// Faster transpiling for minor loose in formatting
compact: true,
// Keep origin information alive
sourceMaps: true,
// Nobody needs the original comments when having source maps
comments: false,
presets:
[
// let, const, destructuring, classes, no modules
[ "babel-preset-es2015", { modules: false }],
// Exponentiation
"babel-preset-es2016",
// Async to generators + trailing function commas
"babel-preset-es2017",
// JSX, Flow
"babel-preset-react"
],
plugins:
[
// Transpile Markdown into React components. Super smart.
"markdown-in-js/babel",
// Optimization for lodash imports.
// Auto cherry-picking es2015 imports from path imports.
"lodash",
// class { handleClick = () => { } }
// https://github.com/tc39/proposal-class-public-fields
"transform-class-properties",
// { ...todo, completed: true }
[ "transform-object-rest-spread", { useBuiltIns: true }],
// Polyfills the runtime needed
[ "transform-runtime", { regenerator: false }],
// Code Splitting by Routes
[
"code-split-component/babel", {
disabled: isDev,
mode: "client"
}
]
]
} : null
return [{
loader: "babel-loader",
options: merge(
{
// Enable caching for babel transpiles
cacheDirectory: true,
env:
{
production: {
comments: false,
plugins: [
// Cleanup descriptions for translations from compilation output
"react-intl",
// Remove prop types from our code
"transform-react-remove-prop-types"
]
},
development: {
plugins: [
// Adds component stack to warning messages
"transform-react-jsx-source",
// Adds __self attribute to JSX which React will use for some warnings
"transform-react-jsx-self",
// Add deprecation messages
"log-deprecated",
// React based
"react-hot-loader/babel"
]
}
}
},
nodeBabel,
webBabel
)
}]
}
function getCssLoaders({ isNode, isWeb, isProd, isDev })
{
// When targetting the node we fake out the style loader as the
// node can't handle the styles and doesn't care about them either..
if (isNode)
{
return [
{
loader: "css-loader/locals",
query:
{
sourceMap: false,
modules: true,
localIdentName: isProd ? "[local]-[hash:base62:8]" : "[path][name]-[local]"
}
},
{
loader: "postcss-loader"
}
]
}
if (isWeb)
{
// For a production client build we use the ExtractTextPlugin which
// will extract our CSS into CSS files. The plugin needs to be
// registered within the plugins section too.
if (isProd)
{
// First: the loader(s) that should be used when the css is not extracted
// Second: the loader(s) that should be used for converting the resource to a css exporting module
// Note: Unfortunately it seems like it does not support the new query syntax of webpack v2
// See also: https://github.com/webpack/extract-text-webpack-plugin/issues/196
return ExtractTextPlugin.extract({
allChunks: true,
fallbackLoader: "style-loader",
loader:
[
{
loader: "css-loader",
query:
{
sourceMap: true,
modules: true,
localIdentName: "[local]-[hash:base62:8]",
minimize: false,
import: false
}
},
{
loader: "postcss-loader"
}
]
})
}
else
{
// For a development client we will use a straight style & css loader
// along with source maps. This combo gives us a better development
// experience.
return [
{
loader: "style-loader"
},
{
loader: "css-loader",
query:
{
sourceMap: true,
modules: true,
localIdentName: "[path][name]-[local]",
minimize: false,
import: false
}
},
{
loader: "postcss-loader"
}
]
}
}
}
const isDebug = true
const isVerbose = true
function ConfigFactory(target, mode, options = {}, root = CWD)
{
// Output custom options
if (Object.keys(options).length > 0) {
console.log("Using options: ", options)
}
if (!target || !~[ "web", "node" ].findIndex((valid) => target === valid))
{
throw new Error(
`You must provide a "target" (web|node) to the ConfigFactory.`
)
}
if (!mode || !~[ "development", "production" ].findIndex((valid) => mode === valid))
{
throw new Error(
`You must provide a "mode" (development|production) to the ConfigFactory.`
)
}
process.env.NODE_ENV = options.debug ? "development" : mode
process.env.BABEL_ENV = mode
const isDev = mode === "development"
const isProd = mode === "production"
const isWeb = target === "web"
const isNode = target === "node"
const ifDev = ifElse(isDev)
const ifProd = ifElse(isProd)
const ifWeb = ifElse(isWeb)
const ifNode = ifElse(isNode)
const ifDevWeb = ifElse(isDev && isWeb)
const ifDevNode = ifElse(isDev && isNode)
const ifProdWeb = ifElse(isProd && isWeb)
const ifProdNode = ifElse(isProd && isNode)
const ifIntegration = ifElse(process.env.CI || false)
const ifUniversal = ifElse(process.env.DISABLE_SSR)
const folder = isWeb ? "client" : "server"
const cssLoaders = getCssLoaders({
isProd,
isDev,
isWeb,
isNode
})
const jsLoaders = getJsLoader({
isProd,
isDev,
isWeb,
isNode
})
const excludeFromTranspilation = [
/node_modules/,
path.resolve(root, process.env.CLIENT_BUNDLE_OUTPUT_PATH),
path.resolve(root, process.env.SERVER_BUNDLE_OUTPUT_PATH)
]
// Just bundle the NodeJS files which are from the local project instead
// of a deep self-contained bundle.
// See also: https://nolanlawson.com/2016/08/15/the-cost-of-small-modules/
const useLightNodeBundle = options.lightBundle == null ? isDev : options.lightBundle
if (useLightNodeBundle && isNode) {
console.log("Using light node bundle")
}
return {
// We need to inform Webpack about our build target
target,
// We have to set this to be able to use these items when executing a
// node bundle. Otherwise strangeness happens, like __dirname resolving
// to '/'. There is no effect on our client bundle.
node: {
__dirname: true,
__filename: true
},
// What information should be printed to the console
stats: {
colors: true,
reasons: isDebug,
hash: isVerbose,
version: isVerbose,
timings: true,
chunks: isVerbose,
chunkModules: isVerbose,
cached: isVerbose,
cachedAssets: isVerbose
},
// This is not the file cache, but the runtime cache.
// The reference is used to speed-up rebuilds in one execution e.g. via watcher
// Note: But is has to share the same configuration as the cache is not config aware.
// cache: cache,
// Capture timing information for each module.
// Analyse tool: http://webpack.github.io/analyse
profile: isProd,
// Report the first error as a hard error instead of tolerating it.
bail: isProd,
// Anything listed in externals will not be included in our bundle.
externals: removeEmpty([
ifNode(function(context, request, callback)
{
var basename = request.split("/")[0]
// Externalize built-in modules
if (builtInSet.has(basename))
return callback(null, "commonjs " + request)
// Keep care that problematic common-js code is external
if (problematicCommonJS.has(basename))
return callback(null, "commonjs " + request)
// Ignore inline files
if (basename.charAt(0) === ".")
return callback()
// But inline all es2015 modules
if (esModules.has(basename))
return callback()
// Inline all files which are dependend on Webpack loaders e.g. CSS, images, etc.
if (isLoaderSpecificFile(request))
return callback()
// In all other cases follow the user given preference
useLightNodeBundle ? callback(null, "commonjs " + request) : callback()
})
]),
// See also: https://webpack.github.io/docs/configuration.html#devtool
// and http://webpack.github.io/docs/build-performance.html#sourcemaps
// All "module*" and "cheap" variants do not seem to work with this kind
// of setup where we have loaders involved. Even simple console messages jump
// to the wrong location in these cases.
devtool: "source-map",
// New performance hints. Only active for production build.
performance: {
hints: isProd && isWeb ? "warning" : false
},
// Define our entry chunks for our bundle.
entry: removeEmptyKeys(
{
main: removeEmpty([
ifDevWeb("react-hot-loader/patch"),
ifDevWeb(`webpack-hot-middleware/client?reload=true&path=http://localhost:${process.env.CLIENT_DEVSERVER_PORT}/__webpack_hmr`),
options.entry ? options.entry : ifIsFile(`./src/${folder}/index.js`),
]),
vendor: ifProdWeb(options.vendor ? options.vendor : ifIsFile(`./src/${folder}/vendor.js`))
}),
output:
{
// The dir in which our bundle should be output.
path: path.resolve(
root,
isWeb ? process.env.CLIENT_BUNDLE_OUTPUT_PATH : process.env.SERVER_BUNDLE_OUTPUT_PATH
),
// The filename format for our bundle's entries.
filename: ifProdWeb(
// We include a hash for client caching purposes. Including a unique
// has for every build will ensure browsers always fetch our newest
// bundle.
"[name]-[chunkhash].js",
// We want a determinable file name when running our NodeJS bundles,
// as we need to be able to target our NodeJS start file from our
// npm scripts. We don't care about caching on the NodeJS anyway.
// We also want our client development builds to have a determinable
// name for our hot reloading client bundle NodeJS.
"[name].js"
),
chunkFilename: ifProdWeb(
"chunk-[name]-[chunkhash].js",
"chunk-[name].js"
),
// This is the web path under which our webpack bundled output should
// be considered as being served from.
publicPath: ifDev(
// As we run a seperate NodeJS for our client and NodeJS bundles we
// need to use an absolute http path for our assets public path.
`http://localhost:${process.env.CLIENT_DEVSERVER_PORT}${process.env.CLIENT_BUNDLE_HTTP_PATH}`,
// Otherwise we expect our bundled output to be served from this path.
process.env.CLIENT_BUNDLE_HTTP_PATH
),
// When in NodeJS mode we will output our bundle as a commonjs2 module.
libraryTarget: ifNode("commonjs2", "var")
},
resolve:
{
// Enable new module/jsnext:main field for requiring files
// Defaults: https://webpack.github.io/docs/configuration.html#resolve-packagemains
mainFields: ifNode(
[ "module", "jsnext:main", "main" ],
[ "web", "browser", "style", "module", "jsnext:main", "main" ]
),
// These extensions are tried when resolving a file.
extensions: [
".js",
".jsx",
".ts",
".tsx",
".css",
".sss",
".json"
]
},
plugins: removeEmpty([
// Offline Plugin working on a automatic fallback based on ServiceWorker and AppCache.
ifProdWeb(new OfflinePlugin()),
// Improve source caching in Webpack v2. Conflicts with offline plugin right now.
// Therefor we disable it in production and only use it to speed up development rebuilds.
/*
ifDev(new HardSourceWebpackPlugin({
// Either an absolute path or relative to output.path.
cacheDirectory: path.resolve(root, ".hardsource", `${target}-${mode}`),
// Either an absolute path or relative to output.path. Sets webpack's
// recordsPath if not already set.
recordsPath: path.resolve(root, ".hardsource", `${target}-${mode}`, "records.json"),
// Optional field. This field determines when to throw away the whole
// cache if for example npm modules were updated.
environmentHash: {
root: root,
directories: [ "node_modules" ],
files: [ "package.json", "yarn.lock" ]
}
})),
*/
// Adds options to all of our loaders.
ifDev(
new webpack.LoaderOptionsPlugin({
// Indicates to our loaders that they should minify their output
// if they have the capability to do so.
minimize: false,
// Indicates to our loaders that they should enter into debug mode
// should they support it.
debug: true,
// Pass options for PostCSS
options: {
postcss: getPostCSSConfig({}),
context: CWD
}
})
),
// Adds options to all of our loaders.
ifProd(
new webpack.LoaderOptionsPlugin({
// Indicates to our loaders that they should minify their output
// if they have the capability to do so.
minimize: true,
// Indicates to our loaders that they should enter into debug mode
// should they support it.
debug: false,
// Pass options for PostCSS
options: {
postcss: getPostCSSConfig({}),
context: CWD
}
})
),
new VerboseProgressPlugin(),
ifProd(new BabiliPlugin({
comments: false,
babili: {
minified: true,
comments: false,
plugins: [
"minify-dead-code-elimination",
"minify-mangle-names",
"minify-simplify"
]
}
})),
new CodeSplitWebpackPlugin({
// The code-split-component doesn't work nicely with hot module reloading,
// which we use in our development builds, so we will disable it if we
// are creating a development bundle (which results in synchronous loading
// behavior on the CodeSplit instances).
disabled: isDev
}),
// Proposed fix to work around issues with CodeSplit vs. HardSource plugin config
// Via: https://github.com/sebastian-software/advanced-boilerplate/compare/master...mzgoddard:code-split-records-compat
{
apply: function(compiler) {
var safeChunkIdMax = 100000
compiler.plugin("compilation", function(compilation) {
compilation.plugin("optimize-chunk-order", function() {
if (compilation.usedChunkIds) {
var usedChunkIds = {}
for (var key in compilation.usedChunkIds) {
if (compilation.usedChunkIds[key] < safeChunkIdMax) {
usedChunkIds[key] = compilation.usedChunkIds[key]
}
}
compilation.usedChunkIds = usedChunkIds
}
})
})
}
},
// For NodeJS bundle, you also want to use "source-map-support" which automatically sourcemaps
// stack traces from NodeJS. We need to install it at the top of the generated file, and we
// can use the BannerPlugin to do this.
// - `raw`: true tells webpack to prepend the text as it is, not wrapping it in a comment.
// - `entryOnly`: false adds the text to all generated files, which you might have multiple if using code splitting.
// Via: http://jlongster.com/Backend-Apps-with-Webpack--Part-I
ifNode(new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true,
entryOnly: false
})),
// Extract vendor bundle for keeping larger parts of the application code
// delivered to users stable during development (improves positive cache hits)
ifProdWeb(new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity
})),
// More aggressive chunk merging strategy. Even similar chunks are merged if the
// total size is reduced enough.
ifProdWeb(new webpack.optimize.AggressiveMergingPlugin()),
// We use this so that our generated [chunkhash]'s are only different if
// the content for our respective chunks have changed. This optimises
// our long term browser caching strategy for our client bundle, avoiding
// cases where browsers end up having to download all the client chunks
// even though 1 or 2 may have only changed.
ifProdWeb(new WebpackDigestHash()),
// Extract chunk hashes into separate file
ifProdWeb(new ChunkManifestPlugin({
filename: "manifest.json",
manifestVariable: "CHUNK_MANIFEST"
})),
// Each key passed into DefinePlugin is an identifier.
// The values for each key will be inlined into the code replacing any
// instances of the keys that are found.
// If the value is a string it will be used as a code fragment.
// If the value isn’t a string, it will be stringified (including functions).
// If the value is an object all keys are removeEmpty the same way.
// If you prefix typeof to the key, it’s only removeEmpty for typeof calls.
new webpack.DefinePlugin({
"process.env.TARGET": JSON.stringify(target),
"process.env.MODE": JSON.stringify(mode),
// NOTE: The NODE_ENV key is especially important for production
// builds as React relies on process.env.NODE_ENV for optimizations.
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
"process.env.APP_ROOT": JSON.stringify(path.resolve(root)),
// All the below items match the config items in our .env file. Go
// to the .env.example for a description of each key.
"process.env.SERVER_PORT": process.env.SERVER_PORT,
"process.env.CLIENT_DEVSERVER_PORT": process.env.CLIENT_DEVSERVER_PORT,
"process.env.DISABLE_SSR": process.env.DISABLE_SSR,
"process.env.SERVER_BUNDLE_OUTPUT_PATH": JSON.stringify(process.env.SERVER_BUNDLE_OUTPUT_PATH),
"process.env.CLIENT_BUNDLE_OUTPUT_PATH": JSON.stringify(process.env.CLIENT_BUNDLE_OUTPUT_PATH),
"process.env.CLIENT_PUBLIC_PATH": JSON.stringify(process.env.CLIENT_PUBLIC_PATH),
"process.env.CLIENT_BUNDLE_ASSETS_FILENAME": JSON.stringify(process.env.CLIENT_BUNDLE_ASSETS_FILENAME),
"process.env.CLIENT_BUNDLE_CHUNK_MANIFEST_FILENAME": JSON.stringify(process.env.CLIENT_BUNDLE_CHUNK_MANIFEST_FILENAME),
"process.env.CLIENT_BUNDLE_HTTP_PATH": JSON.stringify(process.env.CLIENT_BUNDLE_HTTP_PATH),
"process.env.CLIENT_BUNDLE_CACHE_MAXAGE": JSON.stringify(process.env.CLIENT_BUNDLE_CACHE_MAXAGE)
}),
// Generates a JSON file containing a map of all the output files for
// our webpack bundle. A necessisty for our NodeJS rendering process
// as we need to interogate these files in order to know what JS/CSS
// we need to inject into our HTML.
ifWeb(
new AssetsPlugin({
filename: process.env.CLIENT_BUNDLE_ASSETS_FILENAME,
path: path.resolve(root, process.env.CLIENT_BUNDLE_OUTPUT_PATH),
prettyPrint: true
})
),
// Effectively fake all "file-loader" files with placeholders on NodeJS
ifNode(new webpack.NormalModuleReplacementPlugin(
/\.(eot|woff|woff2|ttf|otf|svg|png|jpg|jpeg|gif|webp|webm|mp4|mp3|ogg|html|pdf)$/,
"node-noop"
)),
// We don't want webpack errors to occur during development as it will
// kill our development NodeJS instances.
ifDev(new webpack.NoEmitOnErrorsPlugin()),
// We need this plugin to enable hot module reloading for our dev NodeJS.
ifDevWeb(new webpack.HotModuleReplacementPlugin()),
// This is a production client so we will extract our CSS into
// CSS files.
ifProdWeb(
new ExtractTextPlugin({
filename: "[name]-[contenthash:base62:8].css",
// FIXME: Work on some alternative approach for ExtractText to produce multiple
// external CSS files.
//
// Possibly fork: https://github.com/webpack/extract-text-webpack-plugin
// The current allChunks flag extract all styles from all chunks into one CSS file.
// Without this flag all non entry chunks are keeping their CSS inline in the JS bundle.
//
// Idea: Split into multiple chunk oriented CSS files + load the CSS files during
// from inside the JS file e.g. via calling some external API to load stylesheets.
allChunks: true
})
),
// Analyse webpack bundle
ifProdWeb(new BundleAnalyzerPlugin({
openAnalyzer: false,
analyzerMode: "static"
}))
]),
module:
{
rules: removeEmpty(
[
// JavaScript
{
test: /\.(js|jsx)$/,
loaders: jsLoaders,
exclude: excludeFromTranspilation
},
// Typescript
// https://github.com/s-panferov/awesome-typescript-loader
{
test: /\.(ts|tsx)$/,
loader: "awesome-typescript-loader",
exclude: excludeFromTranspilation
},
// CSS
{
test: /\.css$/,
loader: cssLoaders
},
// JSON
{
test: /\.json$/,
loader: "json-loader"
},
// YAML
{
test: /\.(yml|yaml)$/,
loaders: [ "json-loader", "yaml-loader" ]
},
// References to images, fonts, movies, music, etc.
{
test: /\.(eot|woff|woff2|ttf|otf|svg|png|jpg|jpeg|jp2|jpx|jxr|gif|webp|mp4|mp3|ogg|pdf|html)$/,
loader: "file-loader",
options: {
name: ifProdWeb("file-[hash:base62:8].[ext]", "[name].[ext]"),
emitFile: isWeb
}
},
// GraphQL support
// @see http://dev.apollodata.com/react/webpack.html
{
test: /\.(graphql|gql)$/,
loader: "graphql-tag/loader",
exclude: excludeFromTranspilation
}
])
}
}
}
export default ConfigFactory