webpack.config.dev.js 21 KB

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