UNPKG

9.23 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: [
61 nodeExternals([
62 'instafeed.js',
63 'react-sizeme'
64 ])],
65 output: {
66 // The build folder.
67 path: paths.appBuild,
68 // Generated JS file names (with nested folders).
69 // There will be one main bundle, and one file per asynchronous chunk.
70 // We don't currently advertise code splitting but Webpack supports it.
71 filename: 'index.js',
72 library: '',
73 libraryTarget: 'commonjs',
74 // We inferred the "public path" (such as / or /my-project) from homepage.
75 publicPath: publicPath,
76 // Point sourcemap entries to original disk location (format as URL on Windows)
77 devtoolModuleFilenameTemplate: info =>
78 path
79 .relative(paths.appSrc, info.absoluteResourcePath)
80 .replace(/\\/g, '/'),
81 },
82 resolve: {
83 // This allows you to set a fallback for where Webpack should look for modules.
84 // We placed these paths second because we want `node_modules` to "win"
85 // if there are any conflicts. This matches Node resolution mechanism.
86 // https://github.com/facebookincubator/create-react-app/issues/253
87 modules: ['node_modules', paths.appNodeModules, paths.appSrc].concat(
88 // It is guaranteed to exist because we tweak it in `env.js`
89 process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
90 ),
91 // These are the reasonable defaults supported by the Node ecosystem.
92 // We also include JSX as a common component filename extension to support
93 // some tools, although we do not recommend using it, see:
94 // https://github.com/facebookincubator/create-react-app/issues/290
95 // `web` extension prefixes have been added for better support
96 // for React Native Web.
97 extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
98 alias: {
99
100 // Support React Native Web
101 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
102 'react-native': 'react-native-web',
103 'SRC': paths.appSrc
104 },
105 plugins: [
106 // Prevents users from importing files from outside of src/ (or node_modules/).
107 // This often causes confusion because we only process files within src/ with babel.
108 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
109 // please link the files into your node_modules/ and let module-resolution kick in.
110 // Make sure your source files are compiled, as they will not be processed in any way.
111 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
112 ],
113 },
114 module: {
115 strictExportPresence: true,
116 rules: [
117 // TODO: Disable require.ensure as it's not a standard language feature.
118 // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
119 // { parser: { requireEnsure: false } },
120
121 // First, run the linter.
122 // It's important to do this before Babel processes the JS.
123 {
124 test: /\.(js|jsx|mjs)$/,
125 enforce: 'pre',
126 use: [
127 {
128 options: {
129 formatter: eslintFormatter,
130 eslintPath: require.resolve('eslint'),
131
132 },
133 loader: require.resolve('eslint-loader'),
134 },
135 ],
136 include: paths.appSrc,
137 },
138 {
139 // "oneOf" will traverse all following loaders until one will
140 // match the requirements. When no loader matches it will fall
141 // back to the "file" loader at the end of the loader list.
142 oneOf: [
143 // Process JS with Babel.
144 {
145 test: /\.(js|jsx|mjs)$/,
146 include: paths.appSrc,
147 loader: require.resolve('babel-loader'),
148 options: {
149
150 compact: false,
151 },
152 },
153 ],
154 },
155 ],
156 },
157 plugins: [
158 // Makes some environment variables available to the JS code, for example:
159 // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
160 new webpack.DefinePlugin(env.stringified),
161 // Generate a service worker script that will precache, and keep up to date,
162 // the HTML & assets that are part of the Webpack build.
163 new SWPrecacheWebpackPlugin({
164 // By default, a cache-busting query parameter is appended to requests
165 // used to populate the caches, to ensure the responses are fresh.
166 // If a URL is already hashed by Webpack, then there is no concern
167 // about it being stale, and the cache-busting can be skipped.
168 dontCacheBustUrlsMatching: /\.\w{8}\./,
169 filename: 'service-worker.js',
170 logger(message) {
171 if (message.indexOf('Total precache size is') === 0) {
172 // This message occurs for every build and is a bit too noisy.
173 return;
174 }
175 if (message.indexOf('Skipping static resource') === 0) {
176 // This message obscures real errors so we ignore it.
177 // https://github.com/facebookincubator/create-react-app/issues/2612
178 return;
179 }
180 console.log(message);
181 },
182 minify: false,
183 // For unknown URLs, fallback to the index page
184 navigateFallback: publicUrl + '/index.html',
185 // Ignores URLs starting from /__ (useful for Firebase):
186 // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
187 navigateFallbackWhitelist: [/^(?!\/__).*/],
188 // Don't precache sourcemaps (they're large) and build asset manifest:
189 staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
190 }),
191 // Moment.js is an extremely popular library that bundles large locale files
192 // by default due to how Webpack interprets its code. This is a practical
193 // solution that requires the user to opt into importing specific locales.
194 // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
195 // You can remove this if you don't use Moment.js:
196 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
197 ],
198 // Some libraries import Node modules but don't use them in the browser.
199 // Tell Webpack to provide empty mocks for them so importing them works.
200 node: {
201 dgram: 'empty',
202 fs: 'empty',
203 net: 'empty',
204 tls: 'empty',
205 child_process: 'empty',
206 }
207};