UNPKG

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