-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathwebpack.config.babel.js
431 lines (399 loc) · 12.9 KB
/
webpack.config.babel.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
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import config from './config';
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import StyleLintPlugin from 'stylelint-webpack-plugin';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const { isHot, isDev, isProd } = config;
const { publicPath, apiPath } = config.server;
const src = path.resolve(process.cwd(), 'src');
const dist = path.resolve(process.cwd(), 'dist');
const dll = dist; //path.join(dist, 'dll');
const node_modules = path.resolve(process.cwd(), 'node_modules');
const cssModules = true;
// NOTE: Comment out "console.log" before executing "npm run analyze"
//eslint-disable-next-line no-console
console.log('webpack:',
`NODE_ENV: "${process.env.NODE_ENV}",`,
`isProd: ${config.isProd},`,
`isDev: ${config.isDev},`,
`isTest: ${config.isTest},`,
`isHot: ${config.isHot},`,
`loglevel: "${config.logger.console.level}",`,
`public: "${publicPath}",`,
`api: "${apiPath}"`);
const removeEmptyKeys = obj => {
const result = {};
for (const key in obj) {
if (!(obj[key] === null || obj[key].length === 0)) {
result[key] = obj[key];
}
}
return result;
};
const plugins = () => {
const result = [
// Expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
// inside your code for any environment checks; UglifyJS will automatically
// drop any unreachable code.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.PUBLIC_PATH': JSON.stringify(publicPath),
'process.env.API_PATH': JSON.stringify(apiPath),
__DEV__: isDev,
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnError: isProd
},
context: src, // Required for the sourceMap of css/sass loader
debug: isDev,
minimize: isProd,
},
}),
// Enable scope hoisting
// See: https://webpack.js.org/plugins/module-concatenation-plugin/
// See: https://medium.com/webpack/webpack-3-official-release-15fd2dd8f07b
new webpack.optimize.ModuleConcatenationPlugin(),
new ExtractTextPlugin({
filename: isProd ? '[name].[chunkhash].styles.css' : '[name].styles.css',
allChunks: true,
disable: isHot, // Disable css extracting on development
ignoreOrder: false,
}),
new StyleLintPlugin({
// https://github.com/vieron/stylelint-webpack-plugin
// http://stylelint.io/user-guide/example-config/
configFile: path.resolve(process.cwd(), '.stylelintrc'),
files: '**/*.s?(a|c)ss',
syntax: 'scss',
failOnError: isProd
}),
new StyleLintPlugin({
// https://web-design-weekly.com/2016/06/15/integrate-stylelint-workflow-better-css/
configFile: path.resolve(process.cwd(), '.stylelintrc'),
files: '**/*.css',
failOnError: isProd
}),
new CopyWebpackPlugin([
{ from: 'assets', to: 'assets' }
]),
];
if (isDev) {
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const dllManifest = path.join(dll, 'vendor.dll.manifest.json');
const indexHTML = path.join(src, 'index.html');
if (!fs.existsSync(dllManifest)) {
console.error(chalk.red(`The DLL manifest "${dllManifest}" is missing.`));
console.error(chalk.red('Please run'), chalk.green('`npm run build:dll`'));
process.exit(0);
}
if (!fs.existsSync(indexHTML)) {
console.error(chalk.red(`"${indexHTML}" is missing.`));
process.exit(0);
}
result.push(
new webpack.DllReferencePlugin({
context: dll,
manifest: require(dllManifest)
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new HtmlWebpackPlugin({
template: './index.html',
xhtml: true,
inject: true,
favicon: 'favicon.png',
}),
new AddAssetHtmlPlugin([
{
filepath: path.resolve(dll, 'vendor.styles.css'),
publicPath: publicPath, //path.join(publicPath, 'dll'),
typeOfAsset: 'css'
},
{
filepath: path.resolve(dll, 'vendor.dll.js'),
publicPath: publicPath, //path.join(publicPath, 'dll')
},
]),
);
}
if (isHot) {
result.push(
new webpack.HotModuleReplacementPlugin(
//{
//multiStep: false, // true: Enable multi-pass compilation for enhanced performance in larger projects.
// // NOTE: multiStep: true does not work with webpack3, fails with error:
// // "Server Uncaught Exception TypeError: Cannot read property 'source' of undefined"
// // NOTE: options are experimental and may be deprecated. They are typically not necessary and
// // including a new webpack.HotModuleReplacementPlugin() is enough.
// // See: https://webpack.js.org/plugins/hot-module-replacement-plugin/
//}
),
// Prints more readable module names in the browser console on HMR updates
new webpack.NamedModulesPlugin(),
);
}
if (isProd) {
// Note: do not use '-p' in "build:prod" script
result.push(
// CommonsChunk analyzes everything in your bundles, extracts common bits into files together.
// See: https://webpack.js.org/plugins/commons-chunk-plugin/
// See: https://webpack.js.org/guides/code-splitting-libraries/
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest'],
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true, // Enables tree shaking
dead_code: true, // Enables tree shaking
pure_getters: true,
warnings: false,
screw_ie8: true,
conditionals: true,
comparisons: true,
sequences: true,
evaluate: true,
join_vars: true,
if_return: true,
},
output: {
comments: false
},
sourceMap: true
}),
// Minify and optimize the index.html
new HtmlWebpackPlugin({
template: './index.html',
xhtml: true,
inject: true,
favicon: 'favicon.png',
// Correct bundle order: [manifest, vendor, app]
// see: http://stackoverflow.com/questions/36796319/webpack-with-commonschunkplugin-results-with-wrong-bundle-order-in-html-file
// see: https://github.com/ampedandwired/html-webpack-plugin/issues/481
chunksSortMode: 'dependency',
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
);
}
return result;
};
module.exports = {
name: 'client',
target: 'web', // Make web variables accessible to webpack, e.g. window. This is a default value; just be aware of it
bail: isProd, // Don't attempt to continue if there are any errors.
context: src,
cache: isDev,
devtool: isProd ? 'hidden-source-map' : 'inline-source-map', // or 'cheap-module-eval-source-map'
resolve: {
modules: [
src,
'node_modules'
],
extensions: [
'.js',
'.sass',
'.scss',
'.css',
'.html'
]
},
entry: removeEmptyKeys({
vendor: isProd ? ['./vendor.js'] : [],
app: (isHot
? [
// set reload=true to auto-reload the page when webpack gets stuck.
'webpack-hot-middleware/client?reload=true',
//'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
//'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true',
// You can use full urls, like:
//`webpack-hot-middleware/client?http://${host}:${port}${publicPath}`
// Remember to update path in ./server/index.js - see: Step 3 in ./server/app.js
]
: [])
.concat([
'./index.js',
]),
}),
output: {
filename: isProd ? '[name].[chunkhash].js' : '[name].js', // Don't use hashes in dev mode
chunkFilename: isProd ? '[name].[chunkhash].chunk.js' : '[name].chunk.js',
path: dist,
publicPath: publicPath,
pathinfo: isDev,
},
plugins: plugins(),
module: {
rules: [
{
test: /\.js?$/,
enforce: 'pre',
loader: 'eslint-loader',
include: [src],
exclude: [/node_modules/],
},
{
test: /\.js?$/,
include: [src],
exclude: [/node_modules/],
loader: 'babel-loader',
options: {
cacheDirectory: isDev,
presets: [
[
'env',
{
modules: false,
'debug': false,
}
]
]
}
},
{
test: /\.css$/,
include: [
src,
node_modules
],
exclude: [
path.resolve(process.cwd(), 'src/global.css'),
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
url: true,
sourceMap: true,
importLoaders: 1, // See: https://github.com/webpack-contrib/css-loader#importloaders
modules: cssModules,
localIdentName: '[name]__[local].[hash:base64:5]', //isDev ? '[name]__[local].[hash:base64:5]' : '[hash:base64:5]',
minimize: isProd
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true, // You can set the sourceMap: 'inline' option to inline
// the source map within the CSS directly as an annotation comment.
}
},
//{
// loader: 'resolve-url-loader' // Yields warnings in combination with postcss-cssnext and nested CSS classes
//},
]
})
},
{
test: /\.css$/,
include: [
path.resolve(process.cwd(), 'src/global.css'),
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
url: true,
sourceMap: true,
importLoaders: 1,
modules: false,
minimize: isProd,
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
}
},
{
loader: 'resolve-url-loader'
},
]
})
},
{
test: /\.(scss|sass)$/,
include: [
src,
node_modules
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
url: true,
sourceMap: true,
importLoaders: 2,
modules: cssModules,
localIdentName: '[name]__[local].[hash:base64:5]', //isDev ? '[name]__[local].[hash:base64:5]' : '[hash:base64:5]',
minimize: isProd
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true, // You can set the sourceMap: 'inline' option to inline
// the source map within the CSS directly as an annotation comment.
}
},
//{
// loader: 'resolve-url-loader'
//},
{
loader: 'sass-loader',
options: {
outputStyle: 'expanded',
sourceMap: true,
sourceMapContents: isProd,
}
},
]
})
},
{
test: /\.(jpg|jpeg|gif|png)$/,
loader: 'url-loader?name=[name].[ext]&limit=8192&mimetype=image/[ext]'
},
{
test: /\.svg$/,
loader: 'url-loader?name=[name].[ext]&limit=10240&mimetype=image/svg+xml'
},
{
test: /\.woff[2]?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['url-loader?name=[name].[ext]&limit=10240&mimetype=application/font-[ext]']
},
{
test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['file-loader?name=[name].[ext]&limit=10240&mimetype=application/octet-stream']
},
{
test: /\.otf(\?.*)?$/,
loader: 'file-loader?name=[name].[ext]&limit=10240&mimetype=font/opentype'
},
]
},
};