1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
7 // Do this as the first thing so that any code reading it knows the right env.
8 process.env.BABEL_ENV = 'development';
9 process.env.NODE_ENV = 'development';
11 const fs = require('fs');
12 const path = require('path');
13 const webpack = require('webpack');
14 const resolve = require('resolve');
15 const HtmlWebpackPlugin = require('html-webpack-plugin');
16 const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
17 const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
18 const TerserPlugin = require('terser-webpack-plugin');
19 const MiniCssExtractPlugin = require('mini-css-extract-plugin');
20 const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
21 const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
22 const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
23 const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
24 const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
25 const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
26 const ESLintPlugin = require('eslint-webpack-plugin');
27 const paths = require('./paths');
28 const modules = require('./modules');
29 const getClientEnvironment = require('./env');
30 const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
31 const ForkTsCheckerWebpackPlugin =
32 process.env.TSC_COMPILE_ON_ERROR === 'true'
33 ? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
34 : require('react-dev-utils/ForkTsCheckerWebpackPlugin');
35 const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
37 const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
39 // Source maps are resource heavy and can cause out of memory issue for large source files.
40 const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
42 const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
43 const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
44 '@pmmmwh/react-refresh-webpack-plugin'
46 const babelRuntimeEntry = require.resolve('babel-preset-react-app');
47 const babelRuntimeEntryHelpers = require.resolve(
48 '@babel/runtime/helpers/esm/assertThisInitialized',
49 { paths: [babelRuntimeEntry] }
51 const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
52 paths: [babelRuntimeEntry],
55 // Some apps do not need the benefits of saving a web request, so not inlining the chunk
56 // makes for a smoother build process.
57 const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
59 const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
60 const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
62 const imageInlineSizeLimit = parseInt(
63 process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
66 // Check if TypeScript is setup
67 const useTypeScript = fs.existsSync(paths.appTsConfig);
69 // Check if Tailwind config exists
70 const useTailwind = fs.existsSync(
71 path.join(paths.appPath, 'tailwind.config.js')
74 // Get the path to the uncompiled service worker (if it exists).
75 const swSrc = paths.swSrc;
77 // style files regexes
78 const cssRegex = /\.css$/;
79 const cssModuleRegex = /\.module\.css$/;
80 const sassRegex = /\.(scss|sass)$/;
81 const sassModuleRegex = /\.module\.(scss|sass)$/;
83 const hasJsxRuntime = (() => {
84 if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
89 require.resolve('react/jsx-runtime');
96 // This is the production and development configuration.
97 // It is focused on developer experience, fast rebuilds, and a minimal bundle.
98 module.exports = function (webpackEnv) {
99 const isEnvTest = webpackEnv === 'test';
100 const isEnvDevelopment = webpackEnv === 'development';
101 const isEnvProduction = webpackEnv === 'production';
103 // Variable used for enabling profiling in Production
104 // passed into alias object. Uses a flag if passed into the build command
105 const isEnvProductionProfile =
106 isEnvProduction && process.argv.includes('--profile');
108 // We will provide `paths.publicUrlOrPath` to our app
109 // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
110 // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
111 // Get environment variables to inject into our app.
112 const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
114 const shouldUseReactRefresh = env.raw.FAST_REFRESH;
116 // common function to get style loaders
117 const getStyleLoaders = (cssOptions, preProcessor) => {
119 isEnvDevelopment && require.resolve('style-loader'),
121 loader: MiniCssExtractPlugin.loader,
122 // css is located in `static/css`, use '../../' to locate index.html folder
123 // in production `paths.publicUrlOrPath` can be a relative path
124 options: paths.publicUrlOrPath.startsWith('.')
125 ? { publicPath: '../../' }
129 loader: require.resolve('css-loader'),
133 // Options for PostCSS as we reference these options twice
134 // Adds vendor prefixing based on your specified browser support in
136 loader: require.resolve('postcss-loader'),
139 // Necessary for external CSS imports to work
140 // https://github.com/facebook/create-react-app/issues/2677
143 plugins: !useTailwind
145 'postcss-flexbugs-fixes',
147 'postcss-preset-env',
155 // Adds PostCSS Normalize as the reset css with default options,
156 // so that it honors browserslist config in package.json
157 // which in turn let's users customize the target behavior as per their needs.
162 'postcss-flexbugs-fixes',
164 'postcss-preset-env',
174 sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
181 loader: require.resolve('resolve-url-loader'),
183 sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
188 loader: require.resolve(preProcessor),
199 target: ['browserslist'],
200 mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
201 // Stop compilation early in production
202 bail: isEnvProduction,
203 devtool: isEnvProduction
207 : isEnvDevelopment && 'cheap-module-source-map',
208 // These are the "entry points" to our application.
209 // This means they will be the "root" imports that are included in JS bundle.
210 entry: paths.appIndexJs,
213 path: paths.appBuild,
214 // Add /* filename */ comments to generated require()s in the output.
215 pathinfo: isEnvDevelopment,
216 // There will be one main bundle, and one file per asynchronous chunk.
217 // In development, it does not produce real files.
218 filename: isEnvProduction
219 ? 'static/js/[name].[contenthash:8].js'
220 : isEnvDevelopment && 'static/js/bundle.js',
221 // There are also additional JS chunk files if you use code splitting.
222 chunkFilename: isEnvProduction
223 ? 'static/js/[name].[contenthash:8].chunk.js'
224 : isEnvDevelopment && 'static/js/[name].chunk.js',
225 assetModuleFilename: 'static/media/[name].[hash][ext]',
226 // webpack uses `publicPath` to determine where the app is being served from.
227 // It requires a trailing slash, or the file assets will get an incorrect path.
228 // We inferred the "public path" (such as / or /my-project) from homepage.
229 publicPath: paths.publicUrlOrPath,
230 // Point sourcemap entries to original disk location (format as URL on Windows)
231 devtoolModuleFilenameTemplate: isEnvProduction
234 .relative(paths.appSrc, info.absoluteResourcePath)
236 : isEnvDevelopment || isEnvTest ?
237 (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')) : ()=>null,
241 version: createEnvironmentHash(env.raw),
242 cacheDirectory: paths.appWebpackCache,
245 defaultWebpack: ['webpack/lib/'],
246 config: [__filename],
247 tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
252 infrastructureLogging: {
256 minimize: isEnvProduction,
258 // This is only used in production mode
262 // We want terser to parse ecma 8 code. However, we don't want it
263 // to apply any minification steps that turns valid ecma 5 code
264 // into invalid ecma 5 code. This is why the 'compress' and 'output'
265 // sections only apply transformations that are ecma 5 safe
266 // https://github.com/facebook/create-react-app/pull/4234
272 // Disabled because of an issue with Uglify breaking seemingly valid code:
273 // https://github.com/facebook/create-react-app/issues/2376
274 // Pending further investigation:
275 // https://github.com/mishoo/UglifyJS2/issues/2011
277 // Disabled because of an issue with Terser breaking valid code:
278 // https://github.com/facebook/create-react-app/issues/5250
279 // Pending further investigation:
280 // https://github.com/terser-js/terser/issues/120
286 // Added for profiling in devtools
287 keep_classnames: isEnvProductionProfile,
288 keep_fnames: isEnvProductionProfile,
292 // Turned on because emoji and regex is not minified properly using default
293 // https://github.com/facebook/create-react-app/issues/2488
298 // This is only used in production mode
299 new CssMinimizerPlugin(),
303 // This allows you to set a fallback for where webpack should look for modules.
304 // We placed these paths second because we want `node_modules` to "win"
305 // if there are any conflicts. This matches Node resolution mechanism.
306 // https://github.com/facebook/create-react-app/issues/253
307 modules: ['node_modules', paths.appNodeModules].concat(
308 modules.additionalModulePaths || []
310 fallback: { "path": require.resolve("path-browserify") },
311 // These are the reasonable defaults supported by the Node ecosystem.
312 // We also include JSX as a common component filename extension to support
313 // some tools, although we do not recommend using it, see:
314 // https://github.com/facebook/create-react-app/issues/290
315 // `web` extension prefixes have been added for better support
316 // for React Native Web.
317 extensions: paths.moduleFileExtensions
318 .map(ext => `.${ext}`)
319 .filter(ext => useTypeScript || !ext.includes('ts')),
321 // Support React Native Web
322 // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
323 'react-native': 'react-native-web',
324 // Allows for better profiling with ReactDevTools
325 ...(isEnvProductionProfile && {
326 'react-dom$': 'react-dom/profiling',
327 'scheduler/tracing': 'scheduler/tracing-profiling',
329 ...(modules.webpackAliases || {}),
332 // Prevents users from importing files from outside of src/ (or node_modules/).
333 // This often causes confusion because we only process files within src/ with babel.
334 // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
335 // please link the files into your node_modules/ and let module-resolution kick in.
336 // Make sure your source files are compiled, as they will not be processed in any way.
337 new ModuleScopePlugin(paths.appSrc, [
338 paths.appPackageJson,
339 reactRefreshRuntimeEntry,
340 reactRefreshWebpackPluginRuntimeEntry,
342 babelRuntimeEntryHelpers,
343 babelRuntimeRegenerator,
348 strictExportPresence: true,
350 // Handle node_modules packages that contain sourcemaps
351 shouldUseSourceMap && {
353 exclude: /@babel(?:\/|\\{1,2})runtime/,
354 test: /\.(js|mjs|jsx|ts|tsx|css)$/,
355 loader: require.resolve('source-map-loader'),
358 // "oneOf" will traverse all following loaders until one will
359 // match the requirements. When no loader matches it will fall
360 // back to the "file" loader at the end of the loader list.
362 // TODO: Merge this config once `image/avif` is in the mime-db
363 // https://github.com/jshttp/mime-db
367 mimetype: 'image/avif',
370 maxSize: imageInlineSizeLimit,
374 // "url" loader works like "file" loader except that it embeds assets
375 // smaller than specified limit in bytes as data URLs to avoid requests.
376 // A missing `test` is equivalent to a match.
378 test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
382 maxSize: imageInlineSizeLimit,
390 loader: require.resolve('@svgr/webpack'),
395 plugins: [{ removeViewBox: false }],
402 loader: require.resolve('file-loader'),
404 name: 'static/media/[name].[hash].[ext]',
409 and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
412 // Process application JS with Babel.
413 // The preset includes JSX, Flow, TypeScript, and some ESnext features.
415 test: /\.(js|mjs|jsx|ts|tsx)$/,
416 include: paths.appSrc,
417 loader: require.resolve('babel-loader'),
419 customize: require.resolve(
420 'babel-preset-react-app/webpack-overrides'
424 require.resolve('babel-preset-react-app'),
426 runtime: hasJsxRuntime ? 'automatic' : 'classic',
433 shouldUseReactRefresh &&
434 require.resolve('react-refresh/babel'),
436 // This is a feature of `babel-loader` for webpack (not Babel itself).
437 // It enables caching results in ./node_modules/.cache/babel-loader/
438 // directory for faster rebuilds.
439 cacheDirectory: true,
440 // See #6846 for context on why cacheCompression is disabled
441 cacheCompression: false,
442 compact: isEnvProduction,
445 // Process any JS outside of the app with Babel.
446 // Unlike the application JS, we only compile the standard ES features.
449 exclude: /@babel(?:\/|\\{1,2})runtime/,
450 loader: require.resolve('babel-loader'),
457 require.resolve('babel-preset-react-app/dependencies'),
461 cacheDirectory: true,
462 // See #6846 for context on why cacheCompression is disabled
463 cacheCompression: false,
465 // Babel sourcemaps are needed for debugging into node_modules
466 // code. Without the options below, debuggers like VSCode
467 // show incorrect code and set breakpoints on the wrong lines.
468 sourceMaps: shouldUseSourceMap,
469 inputSourceMap: shouldUseSourceMap,
472 // "postcss" loader applies autoprefixer to our CSS.
473 // "css" loader resolves paths in CSS and adds assets as dependencies.
474 // "style" loader turns CSS into JS modules that inject <style> tags.
475 // In production, we use MiniCSSExtractPlugin to extract that CSS
476 // to a file, but in development "style" loader enables hot editing
478 // By default we support CSS Modules with the extension .module.css
481 exclude: cssModuleRegex,
482 use: getStyleLoaders({
484 sourceMap: isEnvProduction
491 // Don't consider CSS imports dead code even if the
492 // containing package claims to have no side effects.
493 // Remove this when webpack adds a warning or an error for this.
494 // See https://github.com/webpack/webpack/issues/6571
497 // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
498 // using the extension .module.css
500 test: cssModuleRegex,
501 use: getStyleLoaders({
503 sourceMap: isEnvProduction
508 getLocalIdent: getCSSModuleLocalIdent,
512 // Opt-in support for SASS (using .scss or .sass extensions).
513 // By default we support SASS Modules with the
514 // extensions .module.scss or .module.sass
517 exclude: sassModuleRegex,
518 use: getStyleLoaders(
521 sourceMap: isEnvProduction
530 // Don't consider CSS imports dead code even if the
531 // containing package claims to have no side effects.
532 // Remove this when webpack adds a warning or an error for this.
533 // See https://github.com/webpack/webpack/issues/6571
536 // Adds support for CSS Modules, but using SASS
537 // using the extension .module.scss or .module.sass
539 test: sassModuleRegex,
540 use: getStyleLoaders(
543 sourceMap: isEnvProduction
548 getLocalIdent: getCSSModuleLocalIdent,
554 // "file" loader makes sure those assets get served by WebpackDevServer.
555 // When you `import` an asset, you get its (virtual) filename.
556 // In production, they would get copied to the `build` folder.
557 // This loader doesn't use a "test" so it will catch all modules
558 // that fall through the other loaders.
560 // Exclude `js` files to keep "css" loader working as it injects
561 // its runtime that would otherwise be processed through "file" loader.
562 // Also exclude `html` and `json` extensions so they get processed
563 // by webpacks internal loaders.
564 exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
565 type: 'asset/resource',
567 // ** STOP ** Are you adding a new loader?
568 // Make sure to add the new loader(s) before the "file" loader.
574 // Generates an `index.html` file with the <script> injected.
575 new HtmlWebpackPlugin(
580 template: paths.appHtml,
585 removeComments: true,
586 collapseWhitespace: true,
587 removeRedundantAttributes: true,
588 useShortDoctype: true,
589 removeEmptyAttributes: true,
590 removeStyleLinkTypeAttributes: true,
591 keepClosingSlash: true,
600 // Inlines the webpack runtime script. This script is too small to warrant
601 // a network request.
602 // https://github.com/facebook/create-react-app/issues/5358
604 shouldInlineRuntimeChunk &&
605 new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
606 // Makes some environment variables available in index.html.
607 // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
608 // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
609 // It will be an empty string unless you specify "homepage"
610 // in `package.json`, in which case it will be the pathname of that URL.
611 new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
612 // This gives some necessary context to module not found errors, such as
613 // the requesting resource.
614 new ModuleNotFoundPlugin(paths.appPath),
615 // Makes some environment variables available to the JS code, for example:
616 // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
617 // It is absolutely essential that NODE_ENV is set to production
618 // during a production build.
619 // Otherwise React will be compiled in the very slow development mode.
620 new webpack.DefinePlugin(env.stringified),
621 // Experimental hot reloading for React .
622 // https://github.com/facebook/react/tree/main/packages/react-refresh
624 shouldUseReactRefresh &&
625 new ReactRefreshWebpackPlugin({
628 // Watcher doesn't work well if you mistype casing in a path so we use
629 // a plugin that prints an error when you attempt to do this.
630 // See https://github.com/facebook/create-react-app/issues/240
631 isEnvDevelopment && new CaseSensitivePathsPlugin(),
633 new MiniCssExtractPlugin({
634 // Options similar to the same options in webpackOptions.output
635 // both options are optional
636 filename: 'static/css/[name].[contenthash:8].css',
637 chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
639 // Generate an asset manifest file with the following content:
640 // - "files" key: Mapping of all asset filenames to their corresponding
641 // output file so that tools can pick it up without having to parse
643 // - "entrypoints" key: Array of files which are included in `index.html`,
644 // can be used to reconstruct the HTML if necessary
645 new WebpackManifestPlugin({
646 fileName: 'asset-manifest.json',
647 publicPath: paths.publicUrlOrPath,
648 generate: (seed, files, entrypoints) => {
649 const manifestFiles = files.reduce((manifest, file) => {
650 manifest[file.name] = file.path;
653 const entrypointFiles = entrypoints.main.filter(
654 fileName => !fileName.endsWith('.map')
658 files: manifestFiles,
659 entrypoints: entrypointFiles,
663 // Moment.js is an extremely popular library that bundles large locale files
664 // by default due to how webpack interprets its code. This is a practical
665 // solution that requires the user to opt into importing specific locales.
666 // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
667 // You can remove this if you don't use Moment.js:
668 new webpack.IgnorePlugin({
669 resourceRegExp: /^\.\/locale$/,
670 contextRegExp: /moment$/,
672 // Generate a service worker script that will precache, and keep up to date,
673 // the HTML & assets that are part of the webpack build.
675 fs.existsSync(swSrc) &&
676 new WorkboxWebpackPlugin.InjectManifest({
678 dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
679 exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
680 // Bump up the default maximum size (2mb) that's precached,
681 // to make lazy-loading failure scenarios less likely.
682 // See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
683 maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
685 // TypeScript type checking
687 new ForkTsCheckerWebpackPlugin({
688 async: isEnvDevelopment,
690 typescriptPath: resolve.sync('typescript', {
691 basedir: paths.appNodeModules,
695 sourceMap: isEnvProduction
699 inlineSourceMap: false,
700 declarationMap: false,
703 tsBuildInfoFile: paths.appTsBuildInfoFile,
706 context: paths.appPath,
710 mode: 'write-references',
714 // This one is specifically to match during CI tests,
715 // as micromatch doesn't match
716 // '../cra-template-typescript/template/src/App.tsx'
719 { file: '../**/src/**/*.{ts,tsx}' },
720 { file: '**/src/**/*.{ts,tsx}' },
723 { file: '**/src/**/__tests__/**' },
724 { file: '**/src/**/?(*.){spec|test}.*' },
725 { file: '**/src/setupProxy.*' },
726 { file: '**/src/setupTests.*' },
730 infrastructure: 'silent',
733 !disableESLintPlugin &&
736 extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
737 formatter: require.resolve('react-dev-utils/eslintFormatter'),
738 eslintPath: require.resolve('eslint'),
739 failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
740 context: paths.appSrc,
742 cacheLocation: path.resolve(
743 paths.appNodeModules,
744 '.cache/.eslintcache'
746 // ESLint class options
748 resolvePluginsRelativeTo: __dirname,
750 extends: [require.resolve('eslint-config-react-app/base')],
752 ...(!hasJsxRuntime && {
753 'react/react-in-jsx-scope': 'error',
756 ignorePatterns: ['**/*.cy.js'],
760 // Turn off performance processing because we utilize
761 // our own hints via the FileSizeReporter