UNPKG

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