|
| 1 | +import _debug from 'debug' |
| 2 | +import type { Configuration } from 'webpack' |
| 3 | +import reactScriptsPackageJson from 'react-scripts/package.json' |
| 4 | + |
| 5 | +const debug = _debug('@cypress/react:react-scripts') |
| 6 | + |
| 7 | +type DefinePlugin = |
| 8 | + | { definitions: Record<string, Record<string, any>> } |
| 9 | + | undefined; |
| 10 | +type ESLintWebpackPlugin = |
| 11 | + | { options: { baseConfig?: { globals?: Record<string, any> } } } |
| 12 | + | undefined; |
| 13 | + |
| 14 | +export function reactScriptsFiveModifications (webpackConfig: Configuration) { |
| 15 | + // React-Scripts sets the webpack target to ["browserslist"] which tells |
| 16 | + // webpack to target the browsers found within the browserslist config |
| 17 | + // depending on the environment (process.env.NODE_ENV). Since we set |
| 18 | + // process.env.NODE_ENV = "test", webpack is unable to find any browsers and errors. |
| 19 | + // We set BROWSERSLIST_ENV = "development" to override the default NODE_ENV search of browsers. |
| 20 | + if (!process.env.BROWSERSLIST_ENV) { |
| 21 | + process.env.BROWSERSLIST_ENV = 'development' |
| 22 | + } |
| 23 | + |
| 24 | + // We use the "development" configuration of the react-scripts webpack config. |
| 25 | + // There is a conflict when settings process.env.NODE_ENV = "test" since DefinePlugin |
| 26 | + // uses the "development" configuration and expects process.env.NODE_ENV = "development". |
| 27 | + const definePlugin: DefinePlugin = webpackConfig.plugins?.find( |
| 28 | + (plugin) => plugin.constructor.name === 'DefinePlugin' |
| 29 | + ) as unknown as DefinePlugin |
| 30 | + |
| 31 | + if (definePlugin) { |
| 32 | + const processEnv = definePlugin.definitions['process.env'] |
| 33 | + |
| 34 | + processEnv.NODE_ENV = JSON.stringify('development') |
| 35 | + |
| 36 | + debug('Found "DefinePlugin", modified "process.env" definition %o', processEnv) |
| 37 | + } |
| 38 | + |
| 39 | + // React-Scripts v5 no longers uses a loader to configure eslint, so we add globals |
| 40 | + // to the plugin. |
| 41 | + const eslintPlugin = webpackConfig.plugins?.find( |
| 42 | + (plugin) => plugin.constructor.name === 'ESLintWebpackPlugin' |
| 43 | + ) as unknown as ESLintWebpackPlugin |
| 44 | + |
| 45 | + if (eslintPlugin) { |
| 46 | + const cypressGlobals = ['cy', 'Cypress', 'before', 'after', 'context'] |
| 47 | + .reduce((acc, global) => ({ ...acc, [global]: 'writable' }), {}) |
| 48 | + |
| 49 | + eslintPlugin.options.baseConfig = { |
| 50 | + ...eslintPlugin.options.baseConfig, |
| 51 | + globals: { |
| 52 | + ...eslintPlugin.options.baseConfig?.globals, |
| 53 | + ...cypressGlobals, |
| 54 | + }, |
| 55 | + } |
| 56 | + |
| 57 | + debug('Found ESLintWebpackPlugin, modified eslint config %o', eslintPlugin.options.baseConfig) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export const isReactScripts5 = Number(reactScriptsPackageJson.version[0]) >= 5 |
0 commit comments