webpack.config.dev.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. index: [
  81. // Include an alternative client for WebpackDevServer. A client's job is to
  82. // connect to WebpackDevServer by a socket and get notified about changes.
  83. // When you save a file, the client will either apply hot updates (in case
  84. // of CSS changes), or refresh the page (in case of JS changes). When you
  85. // make a syntax error, this client will display a syntax error overlay.
  86. // Note: instead of the default WebpackDevServer client, we use a custom one
  87. // to bring better experience for Create React App users. You can replace
  88. // the line below with these two lines if you prefer the stock client:
  89. // require.resolve('webpack-dev-server/client') + '?/',
  90. // require.resolve('webpack/hot/dev-server'),
  91. require.resolve('react-dev-utils/webpackHotDevClient'),
  92. // Finally, this is your app's code:
  93. paths.appIndexJs,
  94. // We include the app code last so that if there is a runtime error during
  95. // initialization, it doesn't blow up the WebpackDevServer client, and
  96. // changing JS code would still trigger a refresh.
  97. ],
  98. design: [
  99. require.resolve('react-dev-utils/webpackHotDevClient'),
  100. path.resolve(paths.appSrc, "devApp/index.js") //paths.appSrc + "/design.js"
  101. ]
  102. },
  103. output: {
  104. // Add /* filename */ comments to generated require()s in the output.
  105. pathinfo: true,
  106. // This does not produce a real file. It's just the virtual path that is
  107. // served by WebpackDevServer in development. This is the JS bundle
  108. // containing code from all our entry points, and the Webpack runtime.
  109. filename: 'static/js/[name].bundle.js',
  110. // There are also additional JS chunk files if you use code splitting.
  111. chunkFilename: 'static/js/[name].chunk.js',
  112. // This is the URL that app is served from. We use "/" in development.
  113. publicPath: publicPath,
  114. // Point sourcemap entries to original disk location (format as URL on Windows)
  115. devtoolModuleFilenameTemplate: info =>
  116. path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  117. },
  118. optimization: {
  119. // Automatically split vendor and commons
  120. // https://twitter.com/wSokra/status/969633336732905474
  121. // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
  122. splitChunks: {
  123. chunks: 'all',
  124. name: false,
  125. },
  126. // Keep the runtime chunk seperated to enable long term caching
  127. // https://twitter.com/wSokra/status/969679223278505985
  128. runtimeChunk: true,
  129. },
  130. resolve: {
  131. // This allows you to set a fallback for where Webpack should look for modules.
  132. // We placed these paths second because we want `node_modules` to "win"
  133. // if there are any conflicts. This matches Node resolution mechanism.
  134. // https://github.com/facebook/create-react-app/issues/253
  135. modules: ['node_modules'].concat(
  136. // It is guaranteed to exist because we tweak it in `env.js`
  137. process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
  138. ),
  139. // These are the reasonable defaults supported by the Node ecosystem.
  140. // We also include JSX as a common component filename extension to support
  141. // some tools, although we do not recommend using it, see:
  142. // https://github.com/facebook/create-react-app/issues/290
  143. // `web` extension prefixes have been added for better support
  144. // for React Native Web.
  145. extensions: paths.moduleFileExtensions
  146. .map(ext => `.${ext}`)
  147. .filter(ext => useTypeScript || !ext.includes('ts')),
  148. alias: {
  149. // Support React Native Web
  150. // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  151. 'react-native': 'react-native-web',
  152. },
  153. plugins: [
  154. // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  155. // guards against forgotten dependencies and such.
  156. PnpWebpackPlugin,
  157. // Prevents users from importing files from outside of src/ (or node_modules/).
  158. // This often causes confusion because we only process files within src/ with babel.
  159. // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  160. // please link the files into your node_modules/ and let module-resolution kick in.
  161. // Make sure your source files are compiled, as they will not be processed in any way.
  162. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  163. ],
  164. },
  165. resolveLoader: {
  166. plugins: [
  167. // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
  168. // from the current package.
  169. PnpWebpackPlugin.moduleLoader(module),
  170. ],
  171. },
  172. module: {
  173. strictExportPresence: true,
  174. rules: [
  175. // Disable require.ensure as it's not a standard language feature.
  176. {parser: {requireEnsure: false}},
  177. // First, run the linter.
  178. // It's important to do this before Babel processes the JS.
  179. {
  180. test: /\.(js|mjs|jsx)$/,
  181. enforce: 'pre',
  182. use: [
  183. {
  184. options: {
  185. formatter: require.resolve('react-dev-utils/eslintFormatter'),
  186. eslintPath: require.resolve('eslint'),
  187. },
  188. loader: require.resolve('eslint-loader'),
  189. },
  190. ],
  191. include: paths.appSrc,
  192. },
  193. {
  194. // "oneOf" will traverse all following loaders until one will
  195. // match the requirements. When no loader matches it will fall
  196. // back to the "file" loader at the end of the loader list.
  197. oneOf: [
  198. // "url" loader works like "file" loader except that it embeds assets
  199. // smaller than specified limit in bytes as data URLs to avoid requests.
  200. // A missing `test` is equivalent to a match.
  201. {
  202. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  203. loader: require.resolve('url-loader'),
  204. options: {
  205. limit: 10000,
  206. name: 'static/media/[name].[hash:8].[ext]',
  207. },
  208. },
  209. // Process application JS with Babel.
  210. // The preset includes JSX, Flow, and some ESnext features.
  211. {
  212. test: /\.(js|mjs|jsx|ts|tsx)$/,
  213. include: paths.appSrc,
  214. loader: require.resolve('babel-loader'),
  215. options: {
  216. customize: require.resolve(
  217. 'babel-preset-react-app/webpack-overrides'
  218. ),
  219. plugins: [
  220. [
  221. require.resolve('babel-plugin-named-asset-import'),
  222. {
  223. loaderMap: {
  224. svg: {
  225. ReactComponent: '@svgr/webpack?-prettier,-svgo![path]',
  226. },
  227. },
  228. },
  229. ],
  230. ["import", {libraryName: "antd", libraryDirectory: "es", style: "css"}, "ant"],
  231. ["import", { libraryName: "antd-mobile", libraryDirectory: "lib", style: "css"}, "antd-mobile"]
  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. chunks: ["index"],
  340. template: paths.appHtml,
  341. }),
  342. new HtmlWebpackPlugin({
  343. inject: true,
  344. chunks: ["design"],
  345. template: paths.appHtml,
  346. filename: 'design.html',
  347. }),
  348. // Makes some environment variables available in index.html.
  349. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  350. // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  351. // In development, this will be an empty string.
  352. new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  353. // This gives some necessary context to module not found errors, such as
  354. // the requesting resource.
  355. new ModuleNotFoundPlugin(paths.appPath),
  356. // Makes some environment variables available to the JS code, for example:
  357. // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
  358. new webpack.DefinePlugin(env.stringified),
  359. // This is necessary to emit hot updates (currently CSS only):
  360. new webpack.HotModuleReplacementPlugin(),
  361. // Watcher doesn't work well if you mistype casing in a path so we use
  362. // a plugin that prints an error when you attempt to do this.
  363. // See https://github.com/facebook/create-react-app/issues/240
  364. new CaseSensitivePathsPlugin(),
  365. // If you require a missing module and then `npm install` it, you still have
  366. // to restart the development server for Webpack to discover it. This plugin
  367. // makes the discovery automatic so you don't have to restart.
  368. // See https://github.com/facebook/create-react-app/issues/186
  369. new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  370. // Moment.js is an extremely popular library that bundles large locale files
  371. // by default due to how Webpack interprets its code. This is a practical
  372. // solution that requires the user to opt into importing specific locales.
  373. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  374. // You can remove this if you don't use Moment.js:
  375. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  376. // Generate a manifest file which contains a mapping of all asset filenames
  377. // to their corresponding output file so that tools can pick it up without
  378. // having to parse `index.html`.
  379. new ManifestPlugin({
  380. fileName: 'asset-manifest.json',
  381. publicPath: publicPath,
  382. }),
  383. // TypeScript type checking
  384. useTypeScript &&
  385. new ForkTsCheckerWebpackPlugin({
  386. typescript: resolve.sync('typescript', {
  387. basedir: paths.appNodeModules,
  388. }),
  389. async: false,
  390. checkSyntacticErrors: true,
  391. tsconfig: paths.appTsConfig,
  392. compilerOptions: {
  393. module: 'esnext',
  394. moduleResolution: 'node',
  395. resolveJsonModule: true,
  396. isolatedModules: true,
  397. noEmit: true,
  398. jsx: 'preserve',
  399. },
  400. reportFiles: [
  401. '**',
  402. '!**/*.json',
  403. '!**/__tests__/**',
  404. '!**/?(*.)(spec|test).*',
  405. '!src/setupProxy.js',
  406. '!src/setupTests.*',
  407. ],
  408. watch: paths.appSrc,
  409. silent: true,
  410. formatter: typescriptFormatter,
  411. }),
  412. ].filter(Boolean),
  413. // Some libraries import Node modules but don't use them in the browser.
  414. // Tell Webpack to provide empty mocks for them so importing them works.
  415. node: {
  416. dgram: 'empty',
  417. fs: 'empty',
  418. net: 'empty',
  419. tls: 'empty',
  420. child_process: 'empty',
  421. },
  422. // Turn off performance processing because we utilize
  423. // our own hints via the FileSizeReporter
  424. performance: false,
  425. };