UNPKG

9.21 kBJavaScriptView Raw
1'use strict';
2
3const autoprefixer = require('autoprefixer');
4const path = require('path');
5const webpack = require('webpack');
6const ExtractTextPlugin = require('extract-text-webpack-plugin');
7const ManifestPlugin = require('webpack-manifest-plugin');
8const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
9const eslintFormatter = require('react-dev-utils/eslintFormatter');
10const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
11var nodeExternals = require('webpack-node-externals');
12const paths = require('./paths');
13const getClientEnvironment = require('./env');
14
15// Webpack uses `publicPath` to determine where the app is being served from.
16// It requires a trailing slash, or the file assets will get an incorrect path.
17const publicPath = paths.servedPath;
18// Some apps do not use client-side routing with pushState.
19// For these, "homepage" can be set to "." to enable relative asset paths.
20const shouldUseRelativeAssetPaths = publicPath === './';
21// Source maps are resource heavy and can cause out of memory issue for large source files.
22const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
23// `publicUrl` is just like `publicPath`, but we will provide it to our app
24// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
25// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
26const publicUrl = publicPath.slice(0, -1);
27// Get environment variables to inject into our app.
28const env = getClientEnvironment(publicUrl);
29
30// Assert this just to be safe.
31// Development builds of React are slow and not intended for production.
32if (env.stringified['process.env'].NODE_ENV !== '"production"') {
33 throw new Error('Production builds must have NODE_ENV=production.');
34}
35
36// Note: defined here because it will be used more than once.
37const cssFilename = 'static/css/[name].[contenthash:8].css';
38
39// ExtractTextPlugin expects the build output to be flat.
40// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
41// However, our output is structured with css, js and media folders.
42// To have this structure working with relative paths, we have to use custom options.
43const extractTextPluginOptions = shouldUseRelativeAssetPaths
44 ? // Making sure that the publicPath goes back to to build folder.
45 { publicPath: Array(cssFilename.split('/').length).join('../') }
46 : {};
47
48// This is the production configuration.
49// It compiles slowly and is focused on producing a fast and minimal bundle.
50// The development configuration is different and lives in a separate file.
51module.exports = {
52 // Don't attempt to continue if there are any errors.
53 bail: true,
54 // We generate sourcemaps in production. This is slow but gives good results.
55 // You can exclude the *.map files from the build during deployment.
56 devtool: shouldUseSourceMap ? 'source-map' : false,
57 // In production, we only want to load the polyfills and the app code.
58 entry: [require.resolve('./polyfills'), paths.appIndexJs],
59 target: 'node',
60 externals: [nodeExternals(['instafeed.js', 'react-sizeme'])],
61 output: {
62 // The build folder.
63 path: paths.appBuild,
64 // Generated JS file names (with nested folders).
65 // There will be one main bundle, and one file per asynchronous chunk.
66 // We don't currently advertise code splitting but Webpack supports it.
67 filename: 'index.js',
68 library: '',
69 libraryTarget: 'commonjs',
70 // We inferred the "public path" (such as / or /my-project) from homepage.
71 publicPath: publicPath,
72 // Point sourcemap entries to original disk location (format as URL on Windows)
73 devtoolModuleFilenameTemplate: info =>
74 path
75 .relative(paths.appSrc, info.absoluteResourcePath)
76 .replace(/\\/g, '/'),
77 },
78 resolve: {
79 // This allows you to set a fallback for where Webpack should look for modules.
80 // We placed these paths second because we want `node_modules` to "win"
81 // if there are any conflicts. This matches Node resolution mechanism.
82 // https://github.com/facebookincubator/create-react-app/issues/253
83 modules: ['node_modules', paths.appNodeModules, paths.appSrc].concat(
84 // It is guaranteed to exist because we tweak it in `env.js`
85 process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
86 ),
87 // These are the reasonable defaults supported by the Node ecosystem.
88 // We also include JSX as a common component filename extension to support
89 // some tools, although we do not recommend using it, see:
90 // https://github.com/facebookincubator/create-react-app/issues/290
91 // `web` extension prefixes have been added for better support
92 // for React Native Web.
93 extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
94 alias: {
95
96 // Support React Native Web
97 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
98 'react-native': 'react-native-web',
99 'SRC': paths.appSrc
100 },
101 plugins: [
102 // Prevents users from importing files from outside of src/ (or node_modules/).
103 // This often causes confusion because we only process files within src/ with babel.
104 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
105 // please link the files into your node_modules/ and let module-resolution kick in.
106 // Make sure your source files are compiled, as they will not be processed in any way.
107 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
108 ],
109 },
110 module: {
111 strictExportPresence: true,
112 rules: [
113 // TODO: Disable require.ensure as it's not a standard language feature.
114 // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
115 // { parser: { requireEnsure: false } },
116
117 // First, run the linter.
118 // It's important to do this before Babel processes the JS.
119 {
120 test: /\.(js|jsx|mjs)$/,
121 enforce: 'pre',
122 use: [
123 {
124 options: {
125 formatter: eslintFormatter,
126 eslintPath: require.resolve('eslint'),
127
128 },
129 loader: require.resolve('eslint-loader'),
130 },
131 ],
132 include: paths.appSrc,
133 },
134 {
135 // "oneOf" will traverse all following loaders until one will
136 // match the requirements. When no loader matches it will fall
137 // back to the "file" loader at the end of the loader list.
138 oneOf: [
139 // Process JS with Babel.
140 {
141 test: /\.(js|jsx|mjs)$/,
142 include: paths.appSrc,
143 loader: require.resolve('babel-loader'),
144 options: {
145
146 compact: false,
147 },
148 },
149 ],
150 },
151 ],
152 },
153 plugins: [
154 // Makes some environment variables available to the JS code, for example:
155 // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
156 new webpack.DefinePlugin(env.stringified),
157 // Generate a service worker script that will precache, and keep up to date,
158 // the HTML & assets that are part of the Webpack build.
159 new SWPrecacheWebpackPlugin({
160 // By default, a cache-busting query parameter is appended to requests
161 // used to populate the caches, to ensure the responses are fresh.
162 // If a URL is already hashed by Webpack, then there is no concern
163 // about it being stale, and the cache-busting can be skipped.
164 dontCacheBustUrlsMatching: /\.\w{8}\./,
165 filename: 'service-worker.js',
166 logger(message) {
167 if (message.indexOf('Total precache size is') === 0) {
168 // This message occurs for every build and is a bit too noisy.
169 return;
170 }
171 if (message.indexOf('Skipping static resource') === 0) {
172 // This message obscures real errors so we ignore it.
173 // https://github.com/facebookincubator/create-react-app/issues/2612
174 return;
175 }
176 console.log(message);
177 },
178 minify: false,
179 // For unknown URLs, fallback to the index page
180 navigateFallback: publicUrl + '/index.html',
181 // Ignores URLs starting from /__ (useful for Firebase):
182 // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
183 navigateFallbackWhitelist: [/^(?!\/__).*/],
184 // Don't precache sourcemaps (they're large) and build asset manifest:
185 staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
186 }),
187 // Moment.js is an extremely popular library that bundles large locale files
188 // by default due to how Webpack interprets its code. This is a practical
189 // solution that requires the user to opt into importing specific locales.
190 // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
191 // You can remove this if you don't use Moment.js:
192 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
193 ],
194 // Some libraries import Node modules but don't use them in the browser.
195 // Tell Webpack to provide empty mocks for them so importing them works.
196 node: {
197 dgram: 'empty',
198 fs: 'empty',
199 net: 'empty',
200 tls: 'empty',
201 child_process: 'empty',
202 }
203};