UNPKG

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