UNPKG

19.3 kBJavaScriptView Raw
1// @remove-on-eject-begin
2/**
3 * Copyright (c) 2015-present, Facebook, Inc.
4 *
5 * This source code is licensed under the MIT license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8// @remove-on-eject-end
9'use strict';
10
11const autoprefixer = require('autoprefixer');
12const path = require('path');
13const webpack = require('webpack');
14const HtmlWebpackPlugin = require('html-webpack-plugin');
15const ExtractTextPlugin = require('extract-text-webpack-plugin');
16const ManifestPlugin = require('webpack-manifest-plugin');
17const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
18const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
19const eslintFormatter = require('react-dev-utils/eslintFormatter');
20const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
21const paths = require('./paths');
22const getClientEnvironment = require('./env');
23
24// Webpack uses `publicPath` to determine where the app is being served from.
25// It requires a trailing slash, or the file assets will get an incorrect path.
26const publicPath = paths.servedPath;
27// Some apps do not use client-side routing with pushState.
28// For these, "homepage" can be set to "." to enable relative asset paths.
29const shouldUseRelativeAssetPaths = publicPath === './';
30// Source maps are resource heavy and can cause out of memory issue for large source files.
31const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
32// `publicUrl` is just like `publicPath`, but we will provide it to our app
33// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
34// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
35const publicUrl = publicPath.slice(0, -1);
36// Get environment variables to inject into our app.
37const env = getClientEnvironment(publicUrl);
38
39// Assert this just to be safe.
40// Development builds of React are slow and not intended for production.
41if (env.stringified['process.env'].NODE_ENV !== '"production"') {
42 throw new Error('Production builds must have NODE_ENV=production.');
43}
44
45// Note: defined here because it will be used more than once.
46const cssFilename = 'static/css/[name].[contenthash:8].css';
47
48// ExtractTextPlugin expects the build output to be flat.
49// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
50// However, our output is structured with css, js and media folders.
51// To have this structure working with relative paths, we have to use custom options.
52const extractTextPluginOptions = shouldUseRelativeAssetPaths
53 ? // Making sure that the publicPath goes back to to build folder.
54 { publicPath: Array(cssFilename.split('/').length).join('../') }
55 : {};
56
57// This is the production configuration.
58// It compiles slowly and is focused on producing a fast and minimal bundle.
59// The development configuration is different and lives in a separate file.
60module.exports = {
61 // Don't attempt to continue if there are any errors.
62 bail: true,
63 // We generate sourcemaps in production. This is slow but gives good results.
64 // You can exclude the *.map files from the build during deployment.
65 devtool: shouldUseSourceMap ? 'source-map' : false,
66 // In production, we only want to load the polyfills and the app code.
67 entry: [require.resolve('./polyfills'), paths.appIndexJs],
68 output: {
69 // The build folder.
70 path: paths.appBuild,
71 // Generated JS file names (with nested folders).
72 // There will be one main bundle, and one file per asynchronous chunk.
73 // We don't currently advertise code splitting but Webpack supports it.
74 filename: 'static/js/[name].[chunkhash:8].js',
75 chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
76 // We inferred the "public path" (such as / or /my-project) from homepage.
77 publicPath: publicPath,
78 // Point sourcemap entries to original disk location (format as URL on Windows)
79 devtoolModuleFilenameTemplate: info =>
80 path
81 .relative(paths.appSrc, info.absoluteResourcePath)
82 .replace(/\\/g, '/'),
83 },
84 resolve: {
85 // This allows you to set a fallback for where Webpack should look for modules.
86 // We placed these paths second because we want `node_modules` to "win"
87 // if there are any conflicts. This matches Node resolution mechanism.
88 // https://github.com/facebookincubator/create-react-app/issues/253
89 modules: ['node_modules', paths.appNodeModules].concat(
90 // It is guaranteed to exist because we tweak it in `env.js`
91 process.env.NODE_PATH.split(path.delimiter).filter(Boolean),
92 paths.appSrc
93 ),
94 // These are the reasonable defaults supported by the Node ecosystem.
95 // We also include JSX as a common component filename extension to support
96 // some tools, although we do not recommend using it, see:
97 // https://github.com/facebookincubator/create-react-app/issues/290
98 // `web` extension prefixes have been added for better support
99 // for React Native Web.
100 extensions: [
101 '.re',
102 '.ml',
103 '.web.js',
104 '.mjs',
105 '.js',
106 '.json',
107 '.web.jsx',
108 '.jsx',
109 ],
110 alias: {
111 // @remove-on-eject-begin
112 // Resolve Babel runtime relative to react-scripts.
113 // It usually still works on npm 3 without this but it would be
114 // unfortunate to rely on, as react-scripts could be symlinked,
115 // and thus babel-runtime might not be resolvable from the source.
116 'babel-runtime': path.dirname(
117 require.resolve('babel-runtime/package.json')
118 ),
119 // @remove-on-eject-end
120 // Support React Native Web
121 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
122 'react-native': 'react-native-web',
123 },
124 plugins: [
125 // Prevents users from importing files from outside of src/ (or node_modules/).
126 // This often causes confusion because we only process files within src/ with babel.
127 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
128 // please link the files into your node_modules/ and let module-resolution kick in.
129 // Make sure your source files are compiled, as they will not be processed in any way.
130 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
131 ],
132 },
133 module: {
134 strictExportPresence: true,
135 rules: [
136 // TODO: Disable require.ensure as it's not a standard language feature.
137 // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
138 // { parser: { requireEnsure: false } },
139
140 // First, run the linter.
141 // It's important to do this before Babel processes the JS.
142 {
143 test: /\.(js|jsx|mjs)$/,
144 enforce: 'pre',
145 use: [
146 {
147 options: {
148 formatter: eslintFormatter,
149 eslintPath: require.resolve('eslint'),
150 // @remove-on-eject-begin
151 // TODO: consider separate config for production,
152 // e.g. to enable no-console and no-debugger only in production.
153 baseConfig: {
154 extends: [require.resolve('eslint-config-react-app')],
155 },
156 ignore: false,
157 useEslintrc: false,
158 // @remove-on-eject-end
159 },
160 loader: require.resolve('eslint-loader'),
161 },
162 ],
163 include: paths.appSrc,
164 },
165 {
166 // "oneOf" will traverse all following loaders until one will
167 // match the requirements. When no loader matches it will fall
168 // back to the "file" loader at the end of the loader list.
169 oneOf: [
170 // "url" loader works just like "file" loader but it also embeds
171 // assets smaller than specified size as data URLs to avoid requests.
172 {
173 test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
174 loader: require.resolve('url-loader'),
175 options: {
176 limit: 10000,
177 name: 'static/media/[name].[hash:8].[ext]',
178 },
179 },
180 // Process JS with Babel.
181 {
182 test: /\.(js|jsx|mjs)$/,
183 include: paths.appSrc,
184 loader: require.resolve('babel-loader'),
185 options: {
186 // @remove-on-eject-begin
187 babelrc: false,
188 presets: [require.resolve('babel-preset-react-app')],
189 // @remove-on-eject-end
190 compact: true,
191 },
192 },
193 // The notation here is somewhat confusing.
194 // "postcss" loader applies autoprefixer to our CSS.
195 // "css" loader resolves paths in CSS and adds assets as dependencies.
196 // "style" loader normally turns CSS into JS modules injecting <style>,
197 // but unlike in development configuration, we do something different.
198 // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
199 // (second argument), then grabs the result CSS and puts it into a
200 // separate file in our build process. This way we actually ship
201 // a single CSS file in production instead of JS code injecting <style>
202 // tags. If you use code splitting, however, any async bundles will still
203 // use the "style" loader inside the async code so CSS from them won't be
204 // in the main CSS file.
205 {
206 test: /\.css$/,
207 oneOf: [
208 {
209 exclude: paths.appSrc,
210 loader: ExtractTextPlugin.extract(
211 Object.assign(
212 {
213 fallback: {
214 loader: require.resolve('style-loader'),
215 options: {
216 hmr: false,
217 },
218 },
219 use: [
220 {
221 loader: require.resolve('css-loader'),
222 options: {
223 importLoaders: 1,
224 minimize: true,
225 sourceMap: shouldUseSourceMap,
226 },
227 },
228 {
229 loader: require.resolve('postcss-loader'),
230 options: {
231 // Necessary for external CSS imports to work
232 // https://github.com/facebookincubator/create-react-app/issues/2677
233 ident: 'postcss',
234 plugins: () => [
235 require('postcss-flexbugs-fixes'),
236 autoprefixer({
237 browsers: [
238 '>1%',
239 'last 4 versions',
240 'Firefox ESR',
241 'not ie < 9', // React doesn't support IE8 anyway
242 ],
243 flexbox: 'no-2009',
244 }),
245 ],
246 },
247 },
248 ],
249 },
250 extractTextPluginOptions
251 )
252 ),
253 // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
254 },
255 {
256 include: paths.appSrc,
257 loader: ExtractTextPlugin.extract(
258 Object.assign(
259 {
260 fallback: {
261 loader: require.resolve('style-loader'),
262 options: {
263 hmr: false,
264 },
265 },
266 use: [
267 {
268 loader: require.resolve('css-loader'),
269 options: {
270 importLoaders: 1,
271 minimize: true,
272 sourceMap: shouldUseSourceMap,
273 modules: true,
274 },
275 },
276 {
277 loader: require.resolve('postcss-loader'),
278 options: {
279 // Necessary for external CSS imports to work
280 // https://github.com/facebookincubator/create-react-app/issues/2677
281 ident: 'postcss',
282 plugins: () => [
283 require('postcss-flexbugs-fixes'),
284 autoprefixer({
285 browsers: [
286 '>1%',
287 'last 4 versions',
288 'Firefox ESR',
289 'not ie < 9', // React doesn't support IE8 anyway
290 ],
291 flexbox: 'no-2009',
292 }),
293 require('postcss-nested'),
294 require('postcss-simple-vars'),
295 ],
296 },
297 },
298 ],
299 },
300 extractTextPluginOptions
301 )
302 ),
303 // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
304 },
305 ],
306 },
307 {
308 test: /\.(re|rei|ml|mli)$/,
309 use: [
310 {
311 loader: require.resolve('bs-loader'),
312 },
313 ],
314 },
315 // "file" loader makes sure assets end up in the `build` folder.
316 // When you `import` an asset, you get its filename.
317 // This loader doesn't use a "test" so it will catch all modules
318 // that fall through the other loaders.
319 {
320 loader: require.resolve('file-loader'),
321 // Exclude `js` files to keep "css" loader working as it injects
322 // it's runtime that would otherwise processed through "file" loader.
323 // Also exclude `html` and `json` extensions so they get processed
324 // by webpacks internal loaders.
325 exclude: [/\.js$/, /\.html$/, /\.json$/],
326 options: {
327 name: 'static/media/[name].[hash:8].[ext]',
328 },
329 },
330 // ** STOP ** Are you adding a new loader?
331 // Make sure to add the new loader(s) before the "file" loader.
332 ],
333 },
334 ],
335 },
336 plugins: [
337 // Makes some environment variables available in index.html.
338 // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
339 // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
340 // In production, it will be an empty string unless you specify "homepage"
341 // in `package.json`, in which case it will be the pathname of that URL.
342 new InterpolateHtmlPlugin(env.raw),
343 // Generates an `index.html` file with the <script> injected.
344 new HtmlWebpackPlugin({
345 inject: true,
346 template: paths.appHtml,
347 minify: {
348 removeComments: true,
349 collapseWhitespace: true,
350 removeRedundantAttributes: true,
351 useShortDoctype: true,
352 removeEmptyAttributes: true,
353 removeStyleLinkTypeAttributes: true,
354 keepClosingSlash: true,
355 minifyJS: true,
356 minifyCSS: true,
357 minifyURLs: true,
358 },
359 }),
360 // Makes some environment variables available to the JS code, for example:
361 // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
362 // It is absolutely essential that NODE_ENV was set to production here.
363 // Otherwise React will be compiled in the very slow development mode.
364 new webpack.DefinePlugin(env.stringified),
365 // Minify the code.
366 new webpack.optimize.UglifyJsPlugin({
367 compress: {
368 warnings: false,
369 // Disabled because of an issue with Uglify breaking seemingly valid code:
370 // https://github.com/facebookincubator/create-react-app/issues/2376
371 // Pending further investigation:
372 // https://github.com/mishoo/UglifyJS2/issues/2011
373 comparisons: false,
374 },
375 mangle: {
376 safari10: true,
377 },
378 output: {
379 comments: false,
380 // Turned on because emoji and regex is not minified properly using default
381 // https://github.com/facebookincubator/create-react-app/issues/2488
382 ascii_only: true,
383 },
384 sourceMap: shouldUseSourceMap,
385 }),
386 // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
387 new ExtractTextPlugin({
388 filename: cssFilename,
389 }),
390 // Generate a manifest file which contains a mapping of all asset filenames
391 // to their corresponding output file so that tools can pick it up without
392 // having to parse `index.html`.
393 new ManifestPlugin({
394 fileName: 'asset-manifest.json',
395 }),
396 // Generate a service worker script that will precache, and keep up to date,
397 // the HTML & assets that are part of the Webpack build.
398 new SWPrecacheWebpackPlugin({
399 // By default, a cache-busting query parameter is appended to requests
400 // used to populate the caches, to ensure the responses are fresh.
401 // If a URL is already hashed by Webpack, then there is no concern
402 // about it being stale, and the cache-busting can be skipped.
403 dontCacheBustUrlsMatching: /\.\w{8}\./,
404 filename: 'service-worker.js',
405 logger(message) {
406 if (message.indexOf('Total precache size is') === 0) {
407 // This message occurs for every build and is a bit too noisy.
408 return;
409 }
410 if (message.indexOf('Skipping static resource') === 0) {
411 // This message obscures real errors so we ignore it.
412 // https://github.com/facebookincubator/create-react-app/issues/2612
413 return;
414 }
415 console.log(message);
416 },
417 minify: true,
418 // For unknown URLs, fallback to the index page
419 navigateFallback: publicUrl + '/index.html',
420 // Ignores URLs starting from /__ (useful for Firebase):
421 // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
422 navigateFallbackWhitelist: [/^(?!\/__).*/],
423 // Don't precache sourcemaps (they're large) and build asset manifest:
424 staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
425 }),
426 // Moment.js is an extremely popular library that bundles large locale files
427 // by default due to how Webpack interprets its code. This is a practical
428 // solution that requires the user to opt into importing specific locales.
429 // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
430 // You can remove this if you don't use Moment.js:
431 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
432 ],
433 // Some libraries import Node modules but don't use them in the browser.
434 // Tell Webpack to provide empty mocks for them so importing them works.
435 node: {
436 dgram: 'empty',
437 fs: 'empty',
438 net: 'empty',
439 tls: 'empty',
440 child_process: 'empty',
441 },
442};