webpack.config.dev.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. ["import", {libraryName: "antd", libraryDirectory: "es", style: "css"}, "ant"],
  225. ["import", { libraryName: "antd-mobile", libraryDirectory: "lib", style: "css"}, "antd-mobile"]
  226. ],
  227. // This is a feature of `babel-loader` for webpack (not Babel itself).
  228. // It enables caching results in ./node_modules/.cache/babel-loader/
  229. // directory for faster rebuilds.
  230. cacheDirectory: true,
  231. // Don't waste time on Gzipping the cache
  232. cacheCompression: false,
  233. },
  234. },
  235. // Process any JS outside of the app with Babel.
  236. // Unlike the application JS, we only compile the standard ES features.
  237. {
  238. test: /\.(js|mjs)$/,
  239. exclude: /@babel(?:\/|\\{1,2})runtime/,
  240. loader: require.resolve('babel-loader'),
  241. options: {
  242. babelrc: false,
  243. configFile: false,
  244. compact: false,
  245. presets: [
  246. [
  247. require.resolve('babel-preset-react-app/dependencies'),
  248. {helpers: true},
  249. ],
  250. ],
  251. cacheDirectory: true,
  252. // Don't waste time on Gzipping the cache
  253. cacheCompression: false,
  254. // If an error happens in a package, it's possible to be
  255. // because it was compiled. Thus, we don't want the browser
  256. // debugger to show the original code. Instead, the code
  257. // being evaluated would be much more helpful.
  258. sourceMaps: false,
  259. },
  260. },
  261. // "postcss" loader applies autoprefixer to our CSS.
  262. // "css" loader resolves paths in CSS and adds assets as dependencies.
  263. // "style" loader turns CSS into JS modules that inject <style> tags.
  264. // In production, we use a plugin to extract that CSS to a file, but
  265. // in development "style" loader enables hot editing of CSS.
  266. // By default we support CSS Modules with the extension .module.css
  267. {
  268. test: cssRegex,
  269. exclude: cssModuleRegex,
  270. use: getStyleLoaders({
  271. importLoaders: 1,
  272. }),
  273. },
  274. // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
  275. // using the extension .module.css
  276. {
  277. test: cssModuleRegex,
  278. use: getStyleLoaders({
  279. importLoaders: 1,
  280. modules: true,
  281. getLocalIdent: getCSSModuleLocalIdent,
  282. }),
  283. },
  284. // Opt-in support for SASS (using .scss or .sass extensions).
  285. // Chains the sass-loader with the css-loader and the style-loader
  286. // to immediately apply all styles to the DOM.
  287. // By default we support SASS Modules with the
  288. // extensions .module.scss or .module.sass
  289. {
  290. test: sassRegex,
  291. exclude: sassModuleRegex,
  292. use: getStyleLoaders({importLoaders: 2}, 'sass-loader'),
  293. },
  294. // Adds support for CSS Modules, but using SASS
  295. // using the extension .module.scss or .module.sass
  296. {
  297. test: sassModuleRegex,
  298. use: getStyleLoaders(
  299. {
  300. importLoaders: 2,
  301. modules: true,
  302. getLocalIdent: getCSSModuleLocalIdent,
  303. },
  304. 'sass-loader'
  305. ),
  306. },
  307. // "file" loader makes sure those assets get served by WebpackDevServer.
  308. // When you `import` an asset, you get its (virtual) filename.
  309. // In production, they would get copied to the `build` folder.
  310. // This loader doesn't use a "test" so it will catch all modules
  311. // that fall through the other loaders.
  312. {
  313. // Exclude `js` files to keep "css" loader working as it injects
  314. // its runtime that would otherwise be processed through "file" loader.
  315. // Also exclude `html` and `json` extensions so they get processed
  316. // by webpacks internal loaders.
  317. exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
  318. loader: require.resolve('file-loader'),
  319. options: {
  320. name: 'static/media/[name].[hash:8].[ext]',
  321. },
  322. },
  323. ],
  324. },
  325. // ** STOP ** Are you adding a new loader?
  326. // Make sure to add the new loader(s) before the "file" loader.
  327. ],
  328. },
  329. plugins: [
  330. // Generates an `index.html` file with the <script> injected.
  331. new HtmlWebpackPlugin({
  332. inject: true,
  333. template: paths.appHtml,
  334. }),
  335. // Makes some environment variables available in index.html.
  336. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  337. // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  338. // In development, this will be an empty string.
  339. new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  340. // This gives some necessary context to module not found errors, such as
  341. // the requesting resource.
  342. new ModuleNotFoundPlugin(paths.appPath),
  343. // Makes some environment variables available to the JS code, for example:
  344. // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
  345. new webpack.DefinePlugin(env.stringified),
  346. // This is necessary to emit hot updates (currently CSS only):
  347. new webpack.HotModuleReplacementPlugin(),
  348. // Watcher doesn't work well if you mistype casing in a path so we use
  349. // a plugin that prints an error when you attempt to do this.
  350. // See https://github.com/facebook/create-react-app/issues/240
  351. new CaseSensitivePathsPlugin(),
  352. // If you require a missing module and then `npm install` it, you still have
  353. // to restart the development server for Webpack to discover it. This plugin
  354. // makes the discovery automatic so you don't have to restart.
  355. // See https://github.com/facebook/create-react-app/issues/186
  356. new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  357. // Moment.js is an extremely popular library that bundles large locale files
  358. // by default due to how Webpack interprets its code. This is a practical
  359. // solution that requires the user to opt into importing specific locales.
  360. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  361. // You can remove this if you don't use Moment.js:
  362. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  363. // Generate a manifest file which contains a mapping of all asset filenames
  364. // to their corresponding output file so that tools can pick it up without
  365. // having to parse `index.html`.
  366. new ManifestPlugin({
  367. fileName: 'asset-manifest.json',
  368. publicPath: publicPath,
  369. }),
  370. // TypeScript type checking
  371. useTypeScript &&
  372. new ForkTsCheckerWebpackPlugin({
  373. typescript: resolve.sync('typescript', {
  374. basedir: paths.appNodeModules,
  375. }),
  376. async: false,
  377. checkSyntacticErrors: true,
  378. tsconfig: paths.appTsConfig,
  379. compilerOptions: {
  380. module: 'esnext',
  381. moduleResolution: 'node',
  382. resolveJsonModule: true,
  383. isolatedModules: true,
  384. noEmit: true,
  385. jsx: 'preserve',
  386. },
  387. reportFiles: [
  388. '**',
  389. '!**/*.json',
  390. '!**/__tests__/**',
  391. '!**/?(*.)(spec|test).*',
  392. '!src/setupProxy.js',
  393. '!src/setupTests.*',
  394. ],
  395. watch: paths.appSrc,
  396. silent: true,
  397. formatter: typescriptFormatter,
  398. }),
  399. ].filter(Boolean),
  400. // Some libraries import Node modules but don't use them in the browser.
  401. // Tell Webpack to provide empty mocks for them so importing them works.
  402. node: {
  403. dgram: 'empty',
  404. fs: 'empty',
  405. net: 'empty',
  406. tls: 'empty',
  407. child_process: 'empty',
  408. },
  409. // Turn off performance processing because we utilize
  410. // our own hints via the FileSizeReporter
  411. performance: false,
  412. };