webpack.config.dev.js 16 KB

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