[React@18] Env variable to use React@18 (#193113)

Part of
https://github.com/elastic/kibana-team/issues/1016#issuecomment-2454845292

Our plan for React@18 packages upgrade is to let kibana contributors now
that we're going to bump React packages couple weeks in advance. In
addtion to the final PR with green tests and Kibana deployed, we want to
give simple instructions on how to run React@18 locally easilly:

This PR allows to quickly toggle between version of React locally
without having to do anything beyond an environment variable.

`REACT_18=true yarn bootstrap` will alias `react` and `react-dom` to v18
in the build.

I check that this works as expected when starting from: 

- local dev server `yarn start` 
- local ftr `node scripts/functional_tests_server.js`
- local unit tests `REACT_18=true yarn test:jest ...`

Please note: 
- **This PR doesn't implement this switch for dist build, as I don't
think we need this for our purposes.**
- The plan is that we remove this switch soon after we merge React@18
upgrade to main.

In addition to the switch this PR mutes a very noisy warning from
React@18 about legacy root `Warning: ReactDOM.render is no longer
supported in React 18. Use createRoot instead. Until you switch to the
new API, your app will behave as if it's running React 17.`. This
warning is expected as after we upgrade to React@18 packages (Phase 1)
we will be in the process of migrating to the new createRoot API (Phase
2). However, it is very noisy and we want to mute it for now.


Co-authored-by: Anton Dosov <anton.dosov@elastic.co>
This commit is contained in:
Clint Andrew Hall 2024-12-09 06:55:14 -06:00 committed by GitHub
parent ff331f2b6e
commit d0fde5f8e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 190 additions and 17 deletions

1
.github/CODEOWNERS vendored
View file

@ -435,6 +435,7 @@ packages/kbn-plugin-helpers @elastic/kibana-operations
packages/kbn-profiling-utils @elastic/obs-ux-infra_services-team
packages/kbn-react-field @elastic/kibana-data-discovery
packages/kbn-react-hooks @elastic/obs-ux-logs-team
packages/kbn-react-mute-legacy-root-warning @elastic/appex-sharedux
packages/kbn-recently-accessed @elastic/appex-sharedux
packages/kbn-repo-file-maps @elastic/kibana-operations
packages/kbn-repo-info @elastic/kibana-operations

View file

@ -54,6 +54,7 @@ export const command = {
const offline = args.getBooleanValue('offline') ?? false;
const validate = args.getBooleanValue('validate') ?? true;
const quiet = args.getBooleanValue('quiet') ?? false;
const reactVersion = process.env.REACT_18 ? '18' : '17';
const vscodeConfig =
args.getBooleanValue('vscode') ?? (process.env.KBN_BOOTSTRAP_NO_VSCODE ? false : true);
@ -114,7 +115,7 @@ export const command = {
}
await time('pre-build webpack bundles for packages', async () => {
await Bazel.buildWebpackBundles(log, { offline, quiet });
await Bazel.buildWebpackBundles(log, { offline, quiet, reactVersion });
});
await Promise.all([

View file

@ -58,15 +58,19 @@ function throwBazelError(log, name, code, output) {
/**
* @param {import('./log.mjs').Log} log
* @param {string[]} inputArgs
* @param {{ quiet?: boolean; offline?: boolean, env?: Record<string, string> } | undefined} opts
* @param {{ quiet?: boolean; offline?: boolean, reactVersion?: string, env?: Record<string, string> } | undefined} opts
*/
async function runBazel(log, inputArgs, opts = undefined) {
const bazel = (await getBazelRunner()).runBazel;
const args = [...inputArgs, ...(opts?.offline ? ['--config=offline'] : [])];
const args = [
...inputArgs,
`--define=REACT_18=${opts?.reactVersion === '18' ? 'true' : 'false'}`,
...(opts?.offline ? ['--config=offline'] : []),
];
log.debug(`> bazel ${args.join(' ')}`);
await bazel(args, {
env: opts?.env,
env: { ...opts?.env, REACT_18: opts?.reactVersion === '18' ? 'true' : 'false' },
cwd: REPO_ROOT,
quiet: opts?.quiet,
logPrefix: Color.info('[bazel]'),
@ -161,12 +165,13 @@ export async function installYarnDeps(log, opts = undefined) {
/**
* @param {import('./log.mjs').Log} log
* @param {{ offline?: boolean, quiet?: boolean } | undefined} opts
* @param {{ offline?: boolean, quiet?: boolean, reactVersion?: string } | undefined} opts
*/
export async function buildWebpackBundles(log, opts = undefined) {
await runBazel(log, ['build', ...BAZEL_TARGETS, '--show_result=1'], {
offline: opts?.offline,
quiet: opts?.quiet,
reactVersion: opts?.reactVersion,
});
log.success('shared bundles built');

View file

@ -738,6 +738,7 @@
"@kbn/react-kibana-context-styled": "link:packages/react/kibana_context/styled",
"@kbn/react-kibana-context-theme": "link:packages/react/kibana_context/theme",
"@kbn/react-kibana-mount": "link:packages/react/kibana_mount",
"@kbn/react-mute-legacy-root-warning": "link:packages/kbn-react-mute-legacy-root-warning",
"@kbn/recently-accessed": "link:packages/kbn-recently-accessed",
"@kbn/remote-clusters-plugin": "link:x-pack/plugins/remote_clusters",
"@kbn/rendering-plugin": "link:test/plugin_functional/plugins/rendering_plugin",
@ -1227,8 +1228,10 @@
"re-resizable": "^6.9.9",
"re2js": "0.4.3",
"react": "^17.0.2",
"react-18": "npm:react@~18.2.0",
"react-diff-view": "^3.2.1",
"react-dom": "^17.0.2",
"react-dom-18": "npm:react-dom@~18.2.0",
"react-dropzone": "^4.2.9",
"react-fast-compare": "^2.0.4",
"react-grid-layout": "^1.3.4",

View file

@ -40,6 +40,8 @@ import { PluginsService } from '@kbn/core-plugins-browser-internal';
import { CustomBrandingService } from '@kbn/core-custom-branding-browser-internal';
import { SecurityService } from '@kbn/core-security-browser-internal';
import { UserProfileService } from '@kbn/core-user-profile-browser-internal';
import { version as REACT_VERSION } from 'react';
import { muteLegacyRootWarning } from '@kbn/react-mute-legacy-root-warning';
import { KBN_LOAD_MARKS } from './events';
import { fetchOptionalMemoryInfo } from './fetch_optional_memory_info';
import {
@ -128,6 +130,15 @@ export class CoreSystem {
logger: this.loggingSystem.asLoggerFactory(),
};
if (this.coreContext.env.mode.dev && REACT_VERSION.startsWith('18.')) {
muteLegacyRootWarning();
this.coreContext.logger
.get('core-system')
.info(
`Kibana is built with and running React@${REACT_VERSION}, muting legacy root warning.`
);
}
this.i18n = new I18nService();
this.analytics = new AnalyticsService(this.coreContext);
this.fatalErrors = new FatalErrorsService(rootDomElement, () => {

View file

@ -68,6 +68,7 @@
"@kbn/core-user-profile-browser-internal",
"@kbn/core-injected-metadata-common-internal",
"@kbn/core-feature-flags-browser-internal",
"@kbn/react-mute-legacy-root-warning",
],
"exclude": [
"target/**/*",

View file

@ -21,6 +21,7 @@ export interface WorkerConfig {
readonly profileWebpack: boolean;
readonly browserslistEnv: string;
readonly optimizerCacheKey: unknown;
readonly reactVersion: string;
}
export type CacheableWorkerConfig = Omit<WorkerConfig, 'watch' | 'profileWebpack' | 'cache'>;
@ -72,6 +73,11 @@ export function parseWorkerConfig(json: string): WorkerConfig {
throw new Error('`browserslistEnv` must be a string');
}
const reactVersion = parsed.reactVersion;
if (typeof reactVersion !== 'string') {
throw new Error('`reactVersion` must be a string');
}
const themes = parseThemeTags(parsed.themeTags);
return {
@ -83,6 +89,7 @@ export function parseWorkerConfig(json: string): WorkerConfig {
optimizerCacheKey,
browserslistEnv,
themeTags: themes,
reactVersion,
};
} catch (error) {
throw new Error(`unable to parse worker config: ${error.message}`);

View file

@ -88,6 +88,7 @@ describe('getOptimizerCacheKey()', () => {
"browserslistEnv": "dev",
"dist": false,
"optimizerCacheKey": "♻",
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": Array [
"v8light",

View file

@ -98,6 +98,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -126,6 +127,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -154,6 +156,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -181,6 +184,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -209,6 +213,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -237,6 +242,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -265,6 +271,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -294,6 +301,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -323,6 +331,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
@ -385,6 +394,7 @@ describe('OptimizerConfig::create()', () => {
focus: [],
includeCoreBundle: false,
pluginSelector: Symbol('plugin selector'),
reactVersion: 17,
})
);
});
@ -408,6 +418,7 @@ describe('OptimizerConfig::create()', () => {
Symbol(plugin2),
],
"profileWebpack": Symbol(parsed profile webpack),
"reactVersion": 17,
"repoRoot": Symbol(parsed repo root),
"themeTags": Symbol(theme tags),
"watch": Symbol(parsed watch),

View file

@ -119,6 +119,7 @@ export interface ParsedOptions {
includeCoreBundle: boolean;
themeTags: ThemeTags;
pluginSelector: PluginSelector;
reactVersion: string;
}
export class OptimizerConfig {
@ -133,6 +134,7 @@ export class OptimizerConfig {
const includeCoreBundle = !!options.includeCoreBundle;
const filters = options.filter || [];
const focus = options.focus || [];
const reactVersion = process.env.REACT_18 ? '18' : '17';
const repoRoot = options.repoRoot;
if (!Path.isAbsolute(repoRoot)) {
@ -177,6 +179,7 @@ export class OptimizerConfig {
outputRoot,
maxWorkerCount,
profileWebpack,
reactVersion,
cache,
filters,
focus,
@ -234,7 +237,8 @@ export class OptimizerConfig {
options.maxWorkerCount,
options.dist,
options.profileWebpack,
options.themeTags
options.themeTags,
options.reactVersion
);
}
@ -249,7 +253,8 @@ export class OptimizerConfig {
public readonly maxWorkerCount: number,
public readonly dist: boolean,
public readonly profileWebpack: boolean,
public readonly themeTags: ThemeTags
public readonly themeTags: ThemeTags,
public readonly reactVersion: string
) {}
getWorkerConfig(optimizerCacheKey: unknown): WorkerConfig {
@ -262,6 +267,7 @@ export class OptimizerConfig {
optimizerCacheKey,
themeTags: this.themeTags,
browserslistEnv: this.dist ? 'production' : process.env.BROWSERSLIST_ENV || 'dev',
reactVersion: this.reactVersion,
};
}

View file

@ -310,6 +310,10 @@ export function getWebpackConfig(
'src/core/public/styles/core_app/images'
),
vega: Path.resolve(worker.repoRoot, 'node_modules/vega/build-es5/vega.js'),
'react-dom$':
worker.reactVersion === '18' ? 'react-dom-18/profiling' : 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
react: worker.reactVersion === '18' ? 'react-18' : 'react',
},
},

View file

@ -0,0 +1,5 @@
# @kbn/react-mute-legacy-root-warning
After we upgrade to React 18, we will see a warning in the console that we are using the legacy ReactDOM.render API.
This warning is expected as we will be in the process of migrating to the new createRoot API.
However, it is very noisy and we want to mute it for now.

View file

@ -0,0 +1,31 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
/* eslint-disable no-console */
const originalConsoleError = console.error;
/**
* After we upgrade to React 18, we will see a warning in the console that we are using the legacy ReactDOM.render API.
* This warning is expected as we are in the process of migrating to the new createRoot API.
* However, it is very noisy and we want to mute it for now.
*/
export function muteLegacyRootWarning() {
console.error = (message, ...args) => {
if (
typeof message === 'string' &&
message.includes(
"Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17."
)
) {
return;
}
originalConsoleError.call(console, message, ...args);
};
}

View file

@ -0,0 +1,14 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
module.exports = {
preset: '@kbn/test/jest_node',
rootDir: '../..',
roots: ['<rootDir>/packages/kbn-react-mute-legacy-root-warning'],
};

View file

@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/react-mute-legacy-root-warning",
"owner": "@elastic/appex-sharedux"
}

View file

@ -0,0 +1,6 @@
{
"name": "@kbn/react-mute-legacy-root-warning",
"private": true,
"version": "1.0.0",
"license": "Elastic License 2.0 OR AGPL-3.0-only OR SSPL-1.0"
}

View file

@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "target/types",
"types": [
"jest",
"node"
]
},
"include": [
"**/*.ts",
],
"exclude": [
"target/**/*"
],
"kbn_references": []
}

View file

@ -30,6 +30,8 @@ const STATIC_FILE_EXT =
.split('|')
.map((e) => `.${e}`);
const IS_REACT_18 = process.env.REACT_18 === 'true';
/**
* @param {string} request
* @param {import('resolve').SyncOpts} options
@ -69,6 +71,18 @@ module.exports = (request, options) => {
return APM_AGENT_MOCK;
}
// routes tests to the react-18 alias package
if (IS_REACT_18) {
// routes tests to the react-18 alias package
if (/^react?(\/[\s\S]*)?$/.test(request)) {
return module.exports(request.replace('react', 'react-18'), options);
}
if (/^react-dom?(\/[\s\S]*)?$/.test(request)) {
return module.exports(request.replace('react-dom', 'react-dom-18'), options);
}
}
const reqExt = Path.extname(request);
if (reqExt) {
const reqBasename = Path.basename(request, reqExt);

View file

@ -16,6 +16,8 @@ import '@testing-library/jest-dom';
* But since newer versions it has stabilised itself
*/
import { configure } from '@testing-library/react';
import { version as REACT_VERSION } from 'react';
import { muteLegacyRootWarning } from '@kbn/react-mute-legacy-root-warning';
// instead of default 'data-testid', use kibana's 'data-test-subj'
configure({ testIdAttribute: 'data-test-subj', asyncUtilTimeout: 4500 });
@ -52,3 +54,14 @@ console.error = (...args) => {
originalConsoleError(...args);
};
/**
* After we upgrade to React 18, we will see a warning in the console that we are using the legacy ReactDOM.render API.
* This warning is expected as we are in the process of migrating to the new createRoot API.
* However, it is very noisy and we want to mute it for now.
* Tracking issue to clean this up https://github.com/elastic/kibana/issues/199100
*/
if (REACT_VERSION.startsWith('18.')) {
console.warn('Running with React@18 and muting the legacy ReactDOM.render warning');
muteLegacyRootWarning();
}

View file

@ -37,5 +37,6 @@
"@kbn/core-saved-objects-api-server",
"@kbn/mock-idp-utils",
"@kbn/code-owners",
"@kbn/react-mute-legacy-root-warning",
]
}

View file

@ -54,10 +54,12 @@ RUNTIME_DEPS = [
"@npm//lodash",
"@npm//moment-timezone",
"@npm//react-dom",
"@npm//react-dom-18",
"@npm//react-router-dom",
"@npm//react-router-dom-v5-compat",
"@npm//react-router",
"@npm//react",
"@npm//react-18",
"@npm//rxjs",
"@npm//styled-components",
"@npm//tslib",
@ -99,6 +101,7 @@ webpack_cli(
"//conditions:default": {
"NODE_ENV": "development",
"NODE_OPTIONS": "--openssl-legacy-provider",
"REACT_18": "$(REACT_18)",
},
})
)

View file

@ -142,8 +142,10 @@ module.exports = (_, argv) => {
moment: MOMENT_SRC,
// NOTE: Used to include react profiling on bundles
// https://gist.github.com/bvaughn/25e6233aeb1b4f0cdb8d8366e54a3977#webpack-4
'react-dom$': 'react-dom/profiling',
'react-dom$':
process.env.REACT_18 === 'true' ? 'react-dom-18/profiling' : 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
react: process.env.REACT_18 === 'true' ? 'react-18' : 'react',
},
extensions: ['.js', '.ts'],
},

View file

@ -57,6 +57,7 @@ webpack_cli(
"//conditions:default": {
"NODE_ENV": "development",
"NODE_OPTIONS": "--openssl-legacy-provider",
"REACT_18": "$(REACT_18)",
},
}),
visibility = ["//visibility:public"],

View file

@ -112,8 +112,10 @@ module.exports = {
moment: MOMENT_SRC,
// NOTE: Used to include react profiling on bundles
// https://gist.github.com/bvaughn/25e6233aeb1b4f0cdb8d8366e54a3977#webpack-4
'react-dom$': 'react-dom/profiling',
'react-dom$':
process.env.REACT_18 === 'true' ? 'react-dom-18/profiling' : 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
react: process.env.REACT_18 === 'true' ? 'react-18' : 'react',
},
},

View file

@ -1432,6 +1432,8 @@
"@kbn/react-kibana-context-theme/*": ["packages/react/kibana_context/theme/*"],
"@kbn/react-kibana-mount": ["packages/react/kibana_mount"],
"@kbn/react-kibana-mount/*": ["packages/react/kibana_mount/*"],
"@kbn/react-mute-legacy-root-warning": ["packages/kbn-react-mute-legacy-root-warning"],
"@kbn/react-mute-legacy-root-warning/*": ["packages/kbn-react-mute-legacy-root-warning/*"],
"@kbn/recently-accessed": ["packages/kbn-recently-accessed"],
"@kbn/recently-accessed/*": ["packages/kbn-recently-accessed/*"],
"@kbn/remote-clusters-plugin": ["x-pack/plugins/remote_clusters"],

View file

@ -6680,6 +6680,10 @@
version "0.0.0"
uid ""
"@kbn/react-mute-legacy-root-warning@link:packages/kbn-react-mute-legacy-root-warning":
version "0.0.0"
uid ""
"@kbn/recently-accessed@link:packages/kbn-recently-accessed":
version "0.0.0"
uid ""
@ -27358,6 +27362,14 @@ re2js@0.4.3:
resolved "https://registry.yarnpkg.com/re2js/-/re2js-0.4.3.tgz#1318cd0c12aa6ed3ba56d5e012311ffbfb2aef35"
integrity sha512-EuNmh7jurhHEE8Ge/lBo9JuMLb3qf866Xjjfyovw3wPc7+hlqDkZq4LwhrCQMEI+ARWfrKrHozEndzlpNT0WDg==
"react-18@npm:react@~18.2.0", "react@^17.0.0 || ^18.2.0":
name react-18
version "18.2.0"
resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5"
integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==
dependencies:
loose-envify "^1.1.0"
react-clientside-effect@^1.2.6:
version "1.2.6"
resolved "https://registry.yarnpkg.com/react-clientside-effect/-/react-clientside-effect-1.2.6.tgz#29f9b14e944a376b03fb650eed2a754dd128ea3a"
@ -27401,7 +27413,8 @@ react-docgen@^5.0.0:
node-dir "^0.1.10"
strip-indent "^3.0.0"
"react-dom@^17.0.0 || ^18.2.0":
"react-dom-18@npm:react-dom@~18.2.0", "react-dom@^17.0.0 || ^18.2.0":
name react-dom-18
version "18.2.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.2.0.tgz#22aaf38708db2674ed9ada224ca4aa708d821e3d"
integrity sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==
@ -27894,13 +27907,6 @@ react-window@^1.8.10:
"@babel/runtime" "^7.0.0"
memoize-one ">=3.1.1 <6"
"react@^17.0.0 || ^18.2.0":
version "18.2.0"
resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5"
integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==
dependencies:
loose-envify "^1.1.0"
react@^17.0.1, react@^17.0.2:
version "17.0.2"
resolved "https://registry.yarnpkg.com/react/-/react-17.0.2.tgz#d0b5cc516d29eb3eee383f75b62864cfb6800037"