You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

webpack.config.dev.js 19 KiB

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