-
Notifications
You must be signed in to change notification settings - Fork 334
/
createWebpackConfig.js
247 lines (224 loc) · 7.05 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
/**
* Functions for creating a Webpack config with:
*
* - a default set of loaders which can be customised for a particular type of
* build and further tweaked by the end user.
* - a default set of plugins which can be customised for a particular type of
* build and environment, with only configuration or a flag required to enable
* additional pre-selected plugins.
*/
import assert from 'assert'
import path from 'path'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import qs from 'qs'
import webpack, {optimize} from 'webpack'
import merge from 'webpack-merge'
import debug from './debug'
import {findNodeModules, typeOf} from './utils'
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, inclue, exclude}) objects.
*/
export function mergeLoaderConfig(defaultConfig = {}, buildConfig = {}, userConfig = {}) {
let loader = merge(defaultConfig, buildConfig, userConfig)
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) =>
({id, ...mergeLoaderConfig(defaultConfig, buildConfig[id], userConfig[id])})
/**
* Create a default style-handling pipeline for either a static build (default)
* or a server build.
*/
export function createStyleLoader(loader, server, prefix) {
let name = (name) => prefix ? `${prefix}-${name}` : name
let loaders = [
loader(name('css'), {
loader: require.resolve('css-loader')
}),
loader(name('autoprefixer'), {
loader: require.resolve('autoprefixer-loader')
})
]
if (server) {
loaders.unshift(loader(name('style'), {
loader: require.resolve('style-loader')
}))
return combineLoaders(loaders)
}
else {
return ExtractTextPlugin.extract(combineLoaders(loaders))
}
}
export function createLoaders(server, buildConfig = {}, userConfig = {}) {
let loader = loaderConfigFactory(buildConfig, userConfig)
return [
loader('babel', {
test: /\.jsx?$/,
loader: require.resolve('babel-loader'),
exclude: /node_modules/
}),
loader('css-pipeline', {
test: /\.css$/,
loader: createStyleLoader(loader, server),
exclude: /node_modules/
}),
loader('vendor-css-pipeline', {
test: /\.css$/,
loader: createStyleLoader(loader, server, 'vendor'),
include: /node_modules/
}),
loader('graphics', {
test: /\.(gif|png)$/,
loader: require.resolve('url-loader'),
query: {
limit: 10240
}
}),
loader('jpeg', {
test: /\.jpe?g$/,
loader: require.resolve('file-loader')
}),
loader('fonts', {
test: /\.(otf|svg|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: require.resolve('url-loader'),
query: {
limit: 10240
}
}),
loader('eot', {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: require.resolve('file-loader')
}),
loader('json', {
test: /\.json$/,
loader: require.resolve('json-loader')
}),
// Escape hatches for adding new loaders
...buildConfig.extra || [],
...userConfig.extra || []
]
}
/**
* A webpack plugin which forces the build to fail by exiting with a non-zero
* code when there are compilation errors. This is intended for use on a CI
* server which is running webpack builds.
*/
export function failBuildOnCompilationError() {
this.plugin('done', ({compilation}) => {
if (compilation.errors && compilation.errors.length > 0) {
console.error('nwb: webpack build failed:')
compilation.errors.forEach(error => console.error(error.message))
process.exit(1)
}
})
}
export function createPlugins(server, cwd, {
// Banner comment to be added to each generated file in a UMD build
banner,
// Extra constant replacements for DefinePlugin. Since plugins aren't
// currently exposed for user config, it's assumed any user-provided defines
// have already been merged into this.
define,
// Escape hatch for adding new build-specific plugins
extra,
// Options for HtmlWebpackPlugin
html,
// Name to use for a vendor chunk - providing a name causes it to be created.
vendorChunkName
} = {}) {
let plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
...define
}),
new optimize.DedupePlugin(),
new optimize.OccurenceOrderPlugin()
]
// Assumption: we're always hot reloading if we're bundling on the server
if (server) {
plugins.unshift(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
)
}
if (process.env.CONTINUOUS_INTEGRATION === 'true') {
plugins.unshift(failBuildOnCompilationError)
}
if (!server) {
plugins.push(new ExtractTextPlugin(`[name].css`))
}
// Move modules imported from node_modules into a vendor chunk
if (vendorChunkName) {
plugins.push(new optimize.CommonsChunkPlugin({
name: vendorChunkName,
minChunks(module, count) {
return (
module.resource &&
module.resource.indexOf(path.resolve(cwd, 'node_modules')) === 0
)
}
}))
}
if (process.env.NODE_ENV === 'production') {
plugins.push(new optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false
}
}))
}
if (html) {
plugins.push(new HtmlWebpackPlugin({
template: path.join(__dirname, '../templates/webpack-template.html'),
...html
}))
}
if (banner) {
plugins.push(new webpack.BannerPlugin(banner))
}
if (extra) {
plugins = plugins.concat(extra)
}
return plugins
}
/**
* 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(cwd, buildConfig, userConfig = {}) {
assert.equal(typeOf(cwd), 'string', 'cwd is required')
assert.equal(typeOf(buildConfig), 'object', 'buildConfig is required')
debug('createWebpackConfig cwd = %s', cwd)
debug('createWebpackConfig buildConfig = %j', buildConfig)
let {
loaders = {}, plugins = {}, resolve = {}, server = false, ...otherConfig
} = buildConfig
return {
module: {
loaders: createLoaders(server, loaders, userConfig.loaders)
},
plugins: createPlugins(server, cwd, plugins),
resolve: merge({
alias: {
// Alias babel-runtime so it can be found from nwb's dependencies when
// using Babel stage: 0 and optional: ['runtime'] for async/await.
'babel-runtime': path.join(findNodeModules(), 'babel-runtime')
},
extensions: ['', '.web.js', '.js', '.jsx', '.json']
}, resolve),
...otherConfig
}
}