Skip to content

Commit

Permalink
[React@18] Env variable to use React@18 (#193113)
Browse files Browse the repository at this point in the history
Part of
elastic/kibana-team#1016 (comment)

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 <[email protected]>
  • Loading branch information
clintandrewhall and Dosant authored Dec 9, 2024
1 parent ff331f2 commit d0fde5f
Show file tree
Hide file tree
Showing 26 changed files with 190 additions and 17 deletions.
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion kbn_pm/src/commands/bootstrap/bootstrap_command.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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([
Expand Down
13 changes: 9 additions & 4 deletions kbn_pm/src/lib/bazel.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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]'),
Expand Down Expand Up @@ -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');
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
11 changes: 11 additions & 0 deletions packages/core/root/core-root-browser-internal/src/core_system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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, () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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/**/*",
Expand Down
7 changes: 7 additions & 0 deletions packages/kbn-optimizer/src/common/worker_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'>;
Expand Down Expand Up @@ -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 {
Expand All @@ -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}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ describe('getOptimizerCacheKey()', () => {
"browserslistEnv": "dev",
"dist": false,
"optimizerCacheKey": "♻",
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": Array [
"v8light",
Expand Down
11 changes: 11 additions & 0 deletions packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -126,6 +127,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -154,6 +156,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -181,6 +184,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -209,6 +213,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -237,6 +242,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -265,6 +271,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -294,6 +301,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -323,6 +331,7 @@ describe('OptimizerConfig::parseOptions()', () => {
"testPlugins": false,
},
"profileWebpack": false,
"reactVersion": "17",
"repoRoot": <absolute path>,
"themeTags": undefined,
"watch": false,
Expand Down Expand Up @@ -385,6 +394,7 @@ describe('OptimizerConfig::create()', () => {
focus: [],
includeCoreBundle: false,
pluginSelector: Symbol('plugin selector'),
reactVersion: 17,
})
);
});
Expand All @@ -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),
Expand Down
10 changes: 8 additions & 2 deletions packages/kbn-optimizer/src/optimizer/optimizer_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export interface ParsedOptions {
includeCoreBundle: boolean;
themeTags: ThemeTags;
pluginSelector: PluginSelector;
reactVersion: string;
}

export class OptimizerConfig {
Expand All @@ -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)) {
Expand Down Expand Up @@ -177,6 +179,7 @@ export class OptimizerConfig {
outputRoot,
maxWorkerCount,
profileWebpack,
reactVersion,
cache,
filters,
focus,
Expand Down Expand Up @@ -234,7 +237,8 @@ export class OptimizerConfig {
options.maxWorkerCount,
options.dist,
options.profileWebpack,
options.themeTags
options.themeTags,
options.reactVersion
);
}

Expand All @@ -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 {
Expand All @@ -262,6 +267,7 @@ export class OptimizerConfig {
optimizerCacheKey,
themeTags: this.themeTags,
browserslistEnv: this.dist ? 'production' : process.env.BROWSERSLIST_ENV || 'dev',
reactVersion: this.reactVersion,
};
}

Expand Down
4 changes: 4 additions & 0 deletions packages/kbn-optimizer/src/worker/webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
},

Expand Down
5 changes: 5 additions & 0 deletions packages/kbn-react-mute-legacy-root-warning/README.md
Original file line number Diff line number Diff line change
@@ -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.
31 changes: 31 additions & 0 deletions packages/kbn-react-mute-legacy-root-warning/index.ts
Original file line number Diff line number Diff line change
@@ -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);
};
}
14 changes: 14 additions & 0 deletions packages/kbn-react-mute-legacy-root-warning/jest.config.js
Original file line number Diff line number Diff line change
@@ -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'],
};
5 changes: 5 additions & 0 deletions packages/kbn-react-mute-legacy-root-warning/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/react-mute-legacy-root-warning",
"owner": "@elastic/appex-sharedux"
}
6 changes: 6 additions & 0 deletions packages/kbn-react-mute-legacy-root-warning/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
17 changes: 17 additions & 0 deletions packages/kbn-react-mute-legacy-root-warning/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "target/types",
"types": [
"jest",
"node"
]
},
"include": [
"**/*.ts",
],
"exclude": [
"target/**/*"
],
"kbn_references": []
}
Loading

0 comments on commit d0fde5f

Please sign in to comment.