forked from mlaursen/react-md
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebpack.config.js
409 lines (393 loc) · 12.3 KB
/
webpack.config.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
/* eslint-disable no-unused-vars */
const path = require('path');
const dotenv = require('dotenv');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const StartServerPlugin = require('start-server-webpack-plugin');
const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SWPrecachePlugin = require('sw-precache-webpack-plugin');
const SWOfflinePlugin = require('./src/utils/webpack/SWOfflinePlugin');
const ProductionCleanupPlugin = require('./src/utils/webpack/ProductionCleanupPlugin');
const winston = require('winston');
const { name, homepage } = require('./package.json');
dotenv.config();
const src = path.resolve(__dirname, 'src');
const modules = path.resolve(__dirname, 'node_modules');
const clientEntry = path.join(src, 'client', 'index.jsx');
const serverEntry = path.join(src, 'server', 'index.js');
const clientDist = path.resolve(__dirname, 'public');
const serverDist = path.join(__dirname, 'dist');
const SERVICE_WORKER = 'service-worker.js';
const SSR = !!process.env.USE_SSR;
const HOT_RELOAD_PORT = process.env.HOT_RELOAD_PORT || 3001;
const POLL_ENTRY = 'webpack/hot/poll?1000';
const PRODUCTION_SUFFIX = '.[chunkhash:8].min';
const DEV_PLUGINS = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
];
const PROD_PLUGINS = [];
const CLIENT_DEV_PLUGINS = [];
const CLIENT_PROD_PLUGINS = [
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {
screw_ie8: true,
keep_fnames: true,
},
compress: {
screw_ie8: true,
warnings: false,
},
comments: false,
sourceMap: true,
}),
new ProductionCleanupPlugin(),
new ManifestPlugin(),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: ['chunks', 'manifest'],
minChunks: Infinity,
}),
// service workers disabled for awhile until it gets farther along. Too many bugs
// with repeated releases
// Create the offline html fallback page to work with the service workers.
// new HtmlWebpackPlugin({
// filename: 'offline.html',
// inject: true,
// template: path.join(src, 'utils', 'webpack', 'serviceWorkerTemplate.ejs'),
// minify: {
// removeComments: true,
// collapseWhitespace: true,
// removeRedundantAttributes: true,
// useShortDoctype: true,
// removeEmptyAttributes: true,
// removeStyleLinkTypeAttributes: true,
// keepClosingSlash: true,
// minifyJS: true,
// minifyCSS: true,
// minifyURLs: true,
// },
// publicUrl: PUBLIC_URL,
// }),
// // Create a service worker for caching the static assets
// new SWPrecachePlugin({
// cacheId: name,
// // Skip hashing urls when it was already hashed by webpack
// dontCacheBustUrlsMatching: /\.\w{8}\./,
// filename: SERVICE_WORKER,
// minify: true,
// runtimeCaching: [{
// // Cache all the documentation server API calls or the custom themees that get created.
// urlPattern: new RegExp(`^${PUBLIC_URL}/(api|themes)`),
// handler: 'networkFirst',
// }, {
// // Cache all the external fonts/icons
// urlPattern: /^https:\/\/((cdnjs\.cloudflare)|(fonts\.(gstatic|googleapis))\.com)/,
// handler: 'networkFirst',
// }],
// mergeStaticsConfig: true,
// // Include the additional offline service worker hooks to redirect to the
// // offline.html page if the user has no internet connection.
// // Ideally this would use the `chunkName` of `offline` and not require the second plugin,
// // but since the manifest is extracted, it sort of breaks :/
// importScripts: [{ filename: `offline-${SERVICE_WORKER}` }],
// // Skip caching big files
// staticFileGlobsIgnorePatterns: [/\.map$/, /manifest\.json$/],
// }),
// // Create the 'offline-service-worker.js' file that gets imported by the
// // main service worker. This creates an alternative offline html page to
// // use when there is no connection.
// new SWOfflinePlugin({
// cacheId: name,
// entry: path.join(src, 'offline.js'),
// filename: `offline-${SERVICE_WORKER}`,
// }),
];
const SERVER_DEV_PLUGINS = [
new StartServerPlugin({
name: 'server.js',
nodeArgs: [
// '--inspect', // allow node debugging for the server
'-r', 'dotenv/config', // before starting, run dotenv.config
],
}),
];
const SERVER_PROD_PLUGINS = [];
function makeConfig(server, production) {
let publicUrl = process.env.PUBLIC_URL;
if (!publicUrl) {
publicUrl = production ? homepage : 'http://localhost';
winston.info(`The \`PUBLIC_URL\` environment variable was not set. Defaulting to \`${publicUrl}\`.`);
}
if (!publicUrl.match(/^https?:\/\//)) {
winston.info('Updating the `PUBLIC_URL` environment variable to be prefixed with `http://` since the protocol was missing.');
winston.info('Please update the `PUBLIC_URL` environment variable with a valid protocol if this is not desired.');
publicUrl = `http://${publicUrl}`;
}
let publicPath = `${publicUrl}/`;
if (!production) {
publicPath = `${publicUrl}:${HOT_RELOAD_PORT}/`;
}
let dist;
let entry;
let target;
let externals;
let filename;
let chunkFilename;
let nodeTargets;
let browserTargets;
let devServer;
const babelPlugins = [];
const additionalPlugins = [];
const additionalLoaders = [];
if (server) {
const whitelist = [/prismjs.*\.css$/, /webpack-assets\.json$/];
if (!production) {
whitelist.push(POLL_ENTRY);
}
dist = serverDist;
entry = production ? serverEntry : [POLL_ENTRY, serverEntry];
externals = [nodeExternals({ whitelist })];
filename = 'server.js';
target = 'node';
nodeTargets = '6';
additionalPlugins.push(
new webpack.NormalModuleReplacementPlugin(/\.s?css$/, 'node-noop'),
...(production ? SERVER_PROD_PLUGINS : SERVER_DEV_PLUGINS)
);
} else {
const extractStyles = new ExtractTextPlugin({
filename: `styles${PRODUCTION_SUFFIX}.css`,
allChunks: true,
disable: !production && !SSR,
});
dist = clientDist;
entry = clientEntry;
if (!production) {
entry = [
'react-hot-loader/patch',
`webpack-dev-server/client?${publicPath}`,
'webpack/hot/only-dev-server',
entry,
];
}
filename = `[name]${production ? PRODUCTION_SUFFIX : ''}.js`;
chunkFilename = `[name]${production ? PRODUCTION_SUFFIX : ''}.js`;
browserTargets = ['last 2 versions', 'safari >= 7'];
additionalPlugins.push(
extractStyles,
new AssetsPlugin(),
new OptimizeCssAssetsPlugin(),
...(production ? CLIENT_PROD_PLUGINS : CLIENT_DEV_PLUGINS)
);
additionalLoaders.push({
// Loading css dependencies from dependencies (normalize.css and Prism.css)
test: /\.css$/,
loader: extractStyles.extract({
use: [{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 1,
},
}, {
loader: 'postcss-loader',
options: {
sourceMap: true,
},
}],
fallback: 'style-loader',
}),
}, {
test: /\.scss$/,
include: src,
loader: extractStyles.extract({
use: [{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
},
}, {
loader: 'postcss-loader',
options: {
sourceMap: true,
},
}, {
loader: 'sass-loader',
options: {
sourceMap: true,
outputStyle: !production ? 'expanded' : 'compressed',
},
}],
fallback: 'style-loader',
}),
});
babelPlugins.push('react-hot-loader/babel');
devServer = {
host: publicUrl.replace(/https?:\/\/(.+)(:.+)?/, '$1'),
port: HOT_RELOAD_PORT,
historyApiFallback: true,
hot: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
clientLogLevel: 'error',
};
}
if (!production) {
babelPlugins.push('transform-react-jsx-source');
}
const envPresetTargets = {};
if (browserTargets) {
envPresetTargets.browsers = browserTargets;
}
if (nodeTargets) {
envPresetTargets.node = nodeTargets;
}
const routesName = !server && production ? 'async' : 'sync';
winston.info(`Starting compliation with:
- \`publicUrl\` = \`${publicUrl}\`
- \`publicPath\` = \`${publicPath}\`
`);
return {
bail: production,
cache: !production,
devtool: production ? 'source-map' : 'cheap-module-eval-source-map',
devServer,
entry,
target,
externals,
output: {
path: dist,
publicPath,
filename,
chunkFilename,
},
module: {
rules: [{
enforce: 'pre',
test: /\.jsx?$/,
include: src,
loader: 'eslint-loader',
}, {
test: /\.jsx?$/,
include: src,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
['env', {
targets: envPresetTargets,
modules: false,
loose: true,
}],
'react',
'stage-0',
],
plugins: [
...babelPlugins,
'transform-decorators-legacy',
'lodash',
],
},
}, {
test: /\.md$/,
include: src,
loader: 'raw-loader',
}, {
test: /\.json$/,
include: src,
loader: 'json-loader',
}, {
test: /\.(woff2?|ttf|eot)$/,
include: src,
use: [{
loader: 'url-loader',
options: {
limit: 10240,
},
}],
}, {
test: /\.svg$/,
include: path.join(src, 'icons'),
use: [{
loader: 'svg-sprite-loader',
options: {
extract: true,
spriteFilename: `icon-sprites${production ? '.[hash:8]' : ''}.svg`,
},
}, {
loader: 'svgo-loader',
}],
}, {
test: /\.(png|jpe?g|gif|svg)/,
include: src,
exclude: /icons/,
use: [{
loader: 'url-loader',
options: {
limit: 10240,
},
}, {
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true,
},
}],
}, ...additionalLoaders],
},
plugins: [
new webpack.NormalModuleReplacementPlugin(/^routes$/, `routes/${routesName}.js`),
new webpack.NormalModuleReplacementPlugin(/^\.\/routes$/, `./${routesName}.js`),
new webpack.NormalModuleReplacementPlugin(/^\.\/render$/, `./render.${SSR || production ? 'ssr' : 'dev'}.jsx`),
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnError: true,
},
debug: !production,
},
}),
new webpack.DefinePlugin({
PUBLIC_URL: JSON.stringify(publicUrl),
__NGINX__: !!process.env.USE_NGINX,
__DEV__: !production,
__TEST__: false,
__CLIENT__: !server,
__SSR__: production || SSR,
'process.env.NODE_ENV': JSON.stringify(production ? 'production' : 'development'),
}),
new SpriteLoaderPlugin(),
...additionalPlugins,
...(production ? PROD_PLUGINS : DEV_PLUGINS),
],
resolve: {
alias: {
'globals': path.join(src, '_globals.scss'),
'react-md': path.resolve(__dirname, '..'),
'react': path.join(modules, 'react'),
'react-dom': path.join(modules, 'react-dom'),
},
extensions: ['.js', '.jsx'],
// resolve dependencies first and then files in src. Allows for
// import Something from 'components/Something' instead of '../../../../compoennts/Something'
modules: ['node_modules', 'src'],
},
stats: 'errors-only',
};
}
module.exports = ({ production, server }) => {
const config = makeConfig(server, production);
if (production) {
return [config, makeConfig(!server, production)];
}
return config;
};