Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] [React@18] Env variable to use React@18 (#193113) #203419

Merged
merged 2 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ packages/react/kibana_context/root @elastic/appex-sharedux
packages/react/kibana_context/styled @elastic/appex-sharedux
packages/react/kibana_context/theme @elastic/appex-sharedux
packages/react/kibana_mount @elastic/appex-sharedux
packages/kbn-react-mute-legacy-root-warning @elastic/appex-sharedux
packages/kbn-recently-accessed @elastic/appex-sharedux
x-pack/plugins/remote_clusters @elastic/kibana-management
test/plugin_functional/plugins/rendering_plugin @elastic/kibana-core
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 @@ -736,6 +736,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 @@ -1226,8 +1227,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
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 [
"v8dark",
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 @@ -126,6 +126,7 @@ export interface ParsedOptions {
includeCoreBundle: boolean;
themeTags: ThemeTags;
pluginSelector: PluginSelector;
reactVersion: string;
}

export class OptimizerConfig {
Expand All @@ -140,6 +141,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 @@ -184,6 +186,7 @@ export class OptimizerConfig {
outputRoot,
maxWorkerCount,
profileWebpack,
reactVersion,
cache,
filters,
focus,
Expand Down Expand Up @@ -241,7 +244,8 @@ export class OptimizerConfig {
options.maxWorkerCount,
options.dist,
options.profileWebpack,
options.themeTags
options.themeTags,
options.reactVersion
);
}

Expand All @@ -256,7 +260,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 @@ -269,6 +274,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
Loading