UNPKG

19.7 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 path = require('path');
12const webpack = require('webpack');
13const PnpWebpackPlugin = require('pnp-webpack-plugin');
14const HtmlWebpackPlugin = require('html-webpack-plugin');
15const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
16const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
17const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
18const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
19const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
20const getClientEnvironment = require('./env');
21const paths = require('./paths');
22const ManifestPlugin = require('webpack-manifest-plugin');
23const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
24// @remove-on-eject-begin
25const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
26// @remove-on-eject-end
27const CircularDependencyPlugin = require('circular-dependency-plugin');
28
29// Webpack uses `publicPath` to determine where the app is being served from.
30// In development, we always serve from the root. This makes config easier.
31const 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_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
35const publicUrl = '';
36// Get environment variables to inject into our app.
37const env = getClientEnvironment(publicUrl);
38
39// style files regexes
40const cssModuleRegex = /\.css$/;
41const cssGlobalRegex = /\.global\.css$/;
42const sassModuleRegex = /\.(scss|sass)$/;
43const sassGlobalRegex = /\.global\.(scss|sass)$/;
44
45const babelCacheDirectory = process.env.BABEL_CACHE_DIRECTORY ? path.join(paths.appPath, process.env.BABEL_CACHE_DIRECTORY) : true;
46
47// common function to get style loaders
48const getStyleLoaders = (cssOptions, preProcessor) => {
49 const loaders = [
50 require.resolve('style-loader'),
51 {
52 loader: require.resolve('css-loader'),
53 options: cssOptions,
54 },
55 process.env.NODE_ENV === 'test' ? null : {
56 // Options for PostCSS as we reference these options twice
57 // Adds vendor prefixing based on your specified browser support in
58 // package.json
59 loader: require.resolve('postcss-loader'),
60 options: {
61 // Necessary for external CSS imports to work
62 // https://github.com/facebook/create-react-app/issues/2677
63 ident: 'postcss',
64 plugins: () => [
65 require('postcss-flexbugs-fixes'),
66 require('postcss-preset-env')({
67 autoprefixer: {
68 flexbox: 'no-2009',
69 },
70 stage: 3,
71 }),
72 ],
73 },
74 },
75 ].filter(Boolean);
76 if (preProcessor) {
77 loaders.push(require.resolve(preProcessor));
78 }
79 return loaders;
80};
81
82// This is the development configuration.
83// It is focused on developer experience and fast rebuilds.
84// The production configuration is different and lives in a separate file.
85module.exports = {
86 mode: 'development',
87 // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
88 // See the discussion in https://github.com/facebook/create-react-app/issues/343
89 devtool: 'cheap-module-source-map',
90 // These are the "entry points" to our application.
91 // This means they will be the "root" imports that are included in JS bundle.
92 entry: [
93 // Include an alternative client for WebpackDevServer. A client's job is to
94 // connect to WebpackDevServer by a socket and get notified about changes.
95 // When you save a file, the client will either apply hot updates (in case
96 // of CSS changes), or refresh the page (in case of JS changes). When you
97 // make a syntax error, this client will display a syntax error overlay.
98 // Note: instead of the default WebpackDevServer client, we use a custom one
99 // to bring better experience for Create React App users. You can replace
100 // the line below with these two lines if you prefer the stock client:
101 // require.resolve('webpack-dev-server/client') + '?/',
102 // require.resolve('webpack/hot/dev-server'),
103 require.resolve('react-dev-utils/webpackHotDevClient'),
104 // Finally, this is your app's code:
105 paths.appIndexJs,
106 // We include the app code last so that if there is a runtime error during
107 // initialization, it doesn't blow up the WebpackDevServer client, and
108 // changing JS code would still trigger a refresh.
109 ],
110 output: {
111 // Add /* filename */ comments to generated require()s in the output.
112 pathinfo: true,
113 // This does not produce a real file. It's just the virtual path that is
114 // served by WebpackDevServer in development. This is the JS bundle
115 // containing code from all our entry points, and the Webpack runtime.
116 filename: 'static/js/bundle.js',
117 // There are also additional JS chunk files if you use code splitting.
118 chunkFilename: 'static/js/[name].chunk.js',
119 // This is the URL that app is served from. We use "/" in development.
120 publicPath: publicPath,
121 // Point sourcemap entries to original disk location (format as URL on Windows)
122 devtoolModuleFilenameTemplate: info =>
123 path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
124 },
125 optimization: {
126 // Automatically split vendor and commons
127 // https://twitter.com/wSokra/status/969633336732905474
128 // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
129 splitChunks: {
130 chunks: 'all',
131 name: false,
132 },
133 // Keep the runtime chunk seperated to enable long term caching
134 // https://twitter.com/wSokra/status/969679223278505985
135 runtimeChunk: true,
136 },
137 resolve: {
138 // This allows you to set a fallback for where Webpack should look for modules.
139 // We placed these paths second because we want `node_modules` to "win"
140 // if there are any conflicts. This matches Node resolution mechanism.
141 // https://github.com/facebook/create-react-app/issues/253
142 modules: ['node_modules'].concat(
143 // It is guaranteed to exist because we tweak it in `env.js`
144 process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
145 ),
146 // These are the reasonable defaults supported by the Node ecosystem.
147 // We also include JSX as a common component filename extension to support
148 // some tools, although we do not recommend using it, see:
149 // https://github.com/facebook/create-react-app/issues/290
150 // `web` extension prefixes have been added for better support
151 // for React Native Web.
152 extensions: ['.mjs', '.web.js', '.js', '.json', '.web.jsx', '.jsx'],
153 alias: {
154 // Support React Native Web
155 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
156 'react-native': 'react-native-web',
157 },
158 plugins: [
159 // Adds support for installing with Plug'n'Play, leading to faster installs and adding
160 // guards against forgotten dependencies and such.
161 PnpWebpackPlugin,
162 // Prevents users from importing files from outside of src/ (or node_modules/).
163 // This often causes confusion because we only process files within src/ with babel.
164 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
165 // please link the files into your node_modules/ and let module-resolution kick in.
166 // Make sure your source files are compiled, as they will not be processed in any way.
167 new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
168 ],
169 },
170 resolveLoader: {
171 plugins: [
172 // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
173 // from the current package.
174 PnpWebpackPlugin.moduleLoader(module),
175 ],
176 },
177 module: {
178 strictExportPresence: true,
179 rules: [
180 // Disable require.ensure as it's not a standard language feature.
181 { parser: { requireEnsure: false } },
182
183 // First, run the linter.
184 // It's important to do this before Babel processes the JS.
185 !process.env.NO_LINT && {
186 test: /\.(js|mjs|jsx)$/,
187 enforce: 'pre',
188 use: [
189 {
190 options: {
191 formatter: require.resolve('react-dev-utils/eslintFormatter'),
192 eslintPath: require.resolve('eslint'),
193 // @remove-on-eject-begin
194 baseConfig: {
195 extends: [require.resolve('@saritasa/eslint-config-react-app')],
196 settings: { react: { version: '999.999.999' } },
197 },
198 ignore: false,
199 useEslintrc: false,
200 // @remove-on-eject-end
201 },
202 loader: require.resolve('eslint-loader'),
203 },
204 ],
205 include: paths.appSrc,
206 },
207 {
208 // "oneOf" will traverse all following loaders until one will
209 // match the requirements. When no loader matches it will fall
210 // back to the "file" loader at the end of the loader list.
211 oneOf: [
212 // "url" loader works like "file" loader except that it embeds assets
213 // smaller than specified limit in bytes as data URLs to avoid requests.
214 // A missing `test` is equivalent to a match.
215 {
216 test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
217 loader: require.resolve('url-loader'),
218 options: {
219 limit: 10000,
220 name: 'static/media/[name].[hash:8].[ext]',
221 },
222 },
223 // Process application JS with Babel.
224 // The preset includes JSX, Flow, and some ESnext features.
225 {
226 test: /\.(js|mjs|jsx)$/,
227 include: paths.appSrc,
228 loader: require.resolve('babel-loader'),
229 options: {
230 customize: require.resolve(
231 'babel-preset-react-app/webpack-overrides'
232 ),
233 // @remove-on-eject-begin
234 babelrc: false,
235 configFile: false,
236 presets: [require.resolve('@saritasa/babel-preset-react-app')],
237 // Make sure we have a unique cache identifier, erring on the
238 // side of caution.
239 // We remove this when the user ejects because the default
240 // is sane and uses Babel options. Instead of options, we use
241 // the react-scripts and babel-preset-react-app versions.
242 cacheIdentifier: getCacheIdentifier('development', [
243 'babel-plugin-named-asset-import',
244 'babel-preset-react-app',
245 'react-dev-utils',
246 '@saritasa/react-scripts',
247 ]),
248 // @remove-on-eject-end
249 plugins: [
250 [
251 require.resolve('babel-plugin-named-asset-import'),
252 {
253 loaderMap: {
254 svg: {
255 ReactComponent: '@svgr/webpack?-prettier,-svgo![path]',
256 },
257 },
258 },
259 ],
260 ],
261 // This is a feature of `babel-loader` for webpack (not Babel itself).
262 // It enables caching results in ./node_modules/.cache/babel-loader/
263 // directory for faster rebuilds.
264 cacheDirectory: babelCacheDirectory,
265 // Don't waste time on Gzipping the cache
266 cacheCompression: false,
267 },
268 },
269 // Process any JS outside of the app with Babel.
270 // Unlike the application JS, we only compile the standard ES features.
271 {
272 test: /\.(js|mjs)$/,
273 exclude: /@babel(?:\/|\\{1,2})runtime/,
274 loader: require.resolve('babel-loader'),
275 options: {
276 babelrc: false,
277 configFile: false,
278 compact: false,
279 presets: [
280 [
281 require.resolve('@saritasa/babel-preset-react-app/dependencies'),
282 { helpers: true },
283 ],
284 ],
285 cacheDirectory: true,
286 // Don't waste time on Gzipping the cache
287 cacheCompression: false,
288 // @remove-on-eject-begin
289 cacheIdentifier: getCacheIdentifier('development', [
290 'babel-plugin-named-asset-import',
291 'babel-preset-react-app',
292 'react-dev-utils',
293 '@saritasa/react-scripts',
294 ]),
295 // @remove-on-eject-end
296 // If an error happens in a package, it's possible to be
297 // because it was compiled. Thus, we don't want the browser
298 // debugger to show the original code. Instead, the code
299 // being evaluated would be much more helpful.
300 sourceMaps: false,
301 },
302 },
303 // "postcss" loader applies autoprefixer to our CSS.
304 // "css" loader resolves paths in CSS and adds assets as dependencies.
305 // "style" loader turns CSS into JS modules that inject <style> tags.
306 // In production, we use a plugin to extract that CSS to a file, but
307 // in development "style" loader enables hot editing of CSS.
308 // By default we support CSS Modules with the extension .css
309 {
310 test: cssModuleRegex,
311 exclude: cssGlobalRegex,
312 use: getStyleLoaders({
313 importLoaders: 1,
314 modules: true,
315 getLocalIdent: getCSSModuleLocalIdent,
316 }),
317 },
318 // Adds support for global CSS
319 // using the extension .global.css
320 {
321 test: cssGlobalRegex,
322 use: getStyleLoaders({
323 importLoaders: 1,
324 }),
325 },
326 // Opt-in support for SASS (using .scss or .sass extensions).
327 // Chains the sass-loader with the css-loader and the style-loader
328 // to immediately apply all styles to the DOM.
329 // By default we support SASS Modules with the
330 // extensions .scss or .sass
331 {
332 test: sassModuleRegex,
333 exclude: sassGlobalRegex,
334 use: getStyleLoaders(
335 {
336 importLoaders: 2,
337 modules: true,
338 getLocalIdent: getCSSModuleLocalIdent,
339 },
340 'sass-loader'
341 ),
342 },
343 // Adds support for CSS Modules, but using SASS
344 // using the extension .global.scss or .global.sass
345 {
346 test: sassGlobalRegex,
347 use: getStyleLoaders(
348 {
349 importLoaders: 2,
350 },
351 'sass-loader'
352 ),
353 },
354 // The GraphQL loader preprocesses GraphQL queries in .graphql files.
355 {
356 test: /\.(graphql)$/,
357 loader: 'graphql-tag/loader',
358 },
359 // "file" loader makes sure those assets get served by WebpackDevServer.
360 // When you `import` an asset, you get its (virtual) filename.
361 // In production, they would get copied to the `build` folder.
362 // This loader doesn't use a "test" so it will catch all modules
363 // that fall through the other loaders.
364 {
365 // Exclude `js` files to keep "css" loader working as it injects
366 // its runtime that would otherwise be processed through "file" loader.
367 // Also exclude `html` and `json` extensions so they get processed
368 // by webpacks internal loaders.
369 exclude: [/\.(js|mjs|jsx)$/, /\.html$/, /\.json$/],
370 loader: require.resolve('file-loader'),
371 options: {
372 name: 'static/media/[name].[hash:8].[ext]',
373 },
374 },
375 ],
376 },
377 // ** STOP ** Are you adding a new loader?
378 // Make sure to add the new loader(s) before the "file" loader.
379 ].filter(Boolean),
380 },
381 plugins: [
382 // Detects circular dependencies
383 process.env.NODE_ENV === 'test' ? null : new CircularDependencyPlugin({
384 // exclude detection of files based on a RegExp
385 exclude: /node_modules/,
386 // add errors to webpack instead of warnings
387 failOnError: true,
388 // allow import cycles that include an asyncronous import,
389 // e.g. via import(/* webpackMode: "weak" */ './file.js')
390 allowAsyncCycles: false,
391 // set the current working directory for displaying module paths
392 cwd: process.cwd(),
393 }),
394 // Generates an `index.html` file with the <script> injected.
395 new HtmlWebpackPlugin({
396 inject: true,
397 template: paths.appHtml,
398 }),
399 // Makes some environment variables available in index.html.
400 // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
401 // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
402 // In development, this will be an empty string.
403 new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
404 // This gives some necessary context to module not found errors, such as
405 // the requesting resource.
406 process.env.NODE_ENV === 'test' ? null : new ModuleNotFoundPlugin(paths.appPath),
407 // Makes some environment variables available to the JS code, for example:
408 // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
409 new webpack.DefinePlugin(env.stringified),
410 // This is necessary to emit hot updates (currently CSS only):
411 new webpack.HotModuleReplacementPlugin(),
412 // Watcher doesn't work well if you mistype casing in a path so we use
413 // a plugin that prints an error when you attempt to do this.
414 // See https://github.com/facebook/create-react-app/issues/240
415 process.env.NODE_ENV === 'test' ? null : new CaseSensitivePathsPlugin(),
416 // If you require a missing module and then `npm install` it, you still have
417 // to restart the development server for Webpack to discover it. This plugin
418 // makes the discovery automatic so you don't have to restart.
419 // See https://github.com/facebook/create-react-app/issues/186
420 process.env.NODE_ENV === 'test' ? null : new WatchMissingNodeModulesPlugin(paths.appNodeModules),
421 // Moment.js is an extremely popular library that bundles large locale files
422 // by default due to how Webpack interprets its code. This is a practical
423 // solution that requires the user to opt into importing specific locales.
424 // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
425 // You can remove this if you don't use Moment.js:
426 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
427 // Generate a manifest file which contains a mapping of all asset filenames
428 // to their corresponding output file so that tools can pick it up without
429 // having to parse `index.html`.
430 process.env.NODE_ENV === 'test' ? null : new ManifestPlugin({
431 fileName: 'asset-manifest.json',
432 publicPath: publicPath,
433 }),
434 ].filter(Boolean),
435
436 // Some libraries import Node modules but don't use them in the browser.
437 // Tell Webpack to provide empty mocks for them so importing them works.
438 node: {
439 dgram: 'empty',
440 fs: 'empty',
441 net: 'empty',
442 tls: 'empty',
443 child_process: 'empty',
444 },
445 // Turn off performance processing because we utilize
446 // our own hints via the FileSizeReporter
447 performance: false,
448};