Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

fix: upgrade exportMapToHTML and UMD bundle to support React 19 (#3518)

Igor Dykhta760a96492f0f
diff --git a/esbuild/umd-esbuild.config.mjs b/esbuild/umd-esbuild.config.mjs
index def80ef8e..d2f9bceb8 100644
--- a/esbuild/umd-esbuild.config.mjs
+++ b/esbuild/umd-esbuild.config.mjs
@@ -14,6 +14,94 @@ const LIB_DIR = './';
const NODE_MODULES_DIR = join(LIB_DIR, 'node_modules');
const SRC_DIR = join(LIB_DIR, 'src');
+// React 19 removed UMD builds, and the automatic JSX runtime resolves JSX to
+// `react/jsx-runtime` (`jsx`/`jsxs`/`Fragment`) and `react/jsx-dev-runtime`
+// (`jsxDEV`). kepler.gl's own source uses the classic runtime, but several
+// bundled dependencies (e.g. deck.gl React bindings) are precompiled with the
+// automatic runtime, so `require("react/jsx-runtime")` ends up in the UMD
+// output. Since we keep `react` external (a single global `React` provided by
+// the exported HTML), that subpath would resolve to `undefined` at runtime and
+// throw "Cannot read properties of undefined (reading 'jsxs')".
+//
+// This plugin provides a tiny in-bundle implementation of the JSX runtimes that
+// is built on top of the external `React` global (via React.createElement), so
+// no extra global is required and the single React instance is preserved.
+const jsxRuntimeShimPlugin = {
+ name: 'react-jsx-runtime-shim',
+ setup(build) {
+ build.onResolve({filter: /^react\/jsx-(dev-)?runtime$/}, args => ({
+ path: args.path,
+ namespace: 'react-jsx-runtime-shim'
+ }));
+
+ build.onLoad({filter: /.*/, namespace: 'react-jsx-runtime-shim'}, () => ({
+ // `react` stays external here too, so this resolves to the global React.
+ contents: `
+ import * as React from 'react';
+ var createElement = React.createElement;
+ export var Fragment = React.Fragment;
+ function jsxWithKey(type, config, maybeKey) {
+ var props = {};
+ var key = maybeKey === undefined ? null : '' + maybeKey;
+ for (var propName in config) {
+ if (propName !== 'key') props[propName] = config[propName];
+ }
+ if (config && config.key !== undefined && key === null) {
+ key = '' + config.key;
+ }
+ return createElement.apply(null, [type, key === null ? props : Object.assign({key: key}, props)]);
+ }
+ export var jsx = jsxWithKey;
+ export var jsxs = jsxWithKey;
+ export var jsxDEV = jsxWithKey;
+ `,
+ loader: 'js',
+ resolveDir: SRC_DIR
+ }));
+ }
+};
+
+// react-audio-voice-recorder (pulled in transitively via @openassistant/ui for
+// the AI assistant's voice input) ships a prebuilt bundle that vendors a
+// React 17 jsx-runtime. That vendored runtime reads
+// `React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner`
+// at module-eval time WITHOUT optional chaining, which throws under React 19
+// (the property was removed), breaking the whole UMD bundle at load. We only
+// consume its `useAudioRecorder` hook, so we exclude the real package from the
+// UMD bundle and substitute a no-op stub. The exported static map therefore
+// works under React 19; the only lost capability is voice input in the AI
+// assistant (which requires a build tool / npm consumer anyway).
+const audioRecorderStubPlugin = {
+ name: 'react-audio-voice-recorder-stub',
+ setup(build) {
+ build.onResolve({filter: /^react-audio-voice-recorder$/}, args => ({
+ path: args.path,
+ namespace: 'react-audio-voice-recorder-stub'
+ }));
+
+ build.onLoad({filter: /.*/, namespace: 'react-audio-voice-recorder-stub'}, () => ({
+ contents: `
+ export function useAudioRecorder() {
+ return {
+ isRecording: false,
+ recordingBlob: undefined,
+ startRecording: function() {},
+ stopRecording: function() {},
+ togglePauseResume: function() {},
+ recordingTime: 0,
+ isPaused: false,
+ mediaRecorder: undefined
+ };
+ }
+ export function AudioRecorder() { return null; }
+ export default {useAudioRecorder: useAudioRecorder, AudioRecorder: AudioRecorder};
+ `,
+ loader: 'js',
+ resolveDir: SRC_DIR
+ }));
+ }
+};
+
const config = {
entryPoints: ['./src/index.js'],
bundle: true,
@@ -25,9 +113,19 @@ const config = {
sourcemap: false,
treeShaking: true,
+ // React 19+ no longer ships UMD builds, but the kepler.gl UMD bundle keeps
+ // these dependencies external and expects them as globals on `window`
+ // (React, ReactDOM, Redux, ReactRedux, styled). The exported static HTML map
+ // (see src/utils/src/export-map-html.ts) provides these globals by loading the
+ // corresponding ES modules from an ESM CDN through an import map. Keep the list
+ // of externals and the globals map below in sync with that template.
+ // Note: `react/jsx-runtime` is intentionally NOT external; it is shimmed on top
+ // of the external `React` global by jsxRuntimeShimPlugin below.
external: ['react', 'react-dom', 'redux', 'react-redux', 'styled-components'],
plugins: [
+ jsxRuntimeShimPlugin,
+ audioRecorderStubPlugin,
// automatically injected kepler.gl package version into the bundle
replace({
__PACKAGE_VERSION__: KeplerPackage.version,
diff --git a/src/utils/src/export-map-html.ts b/src/utils/src/export-map-html.ts
index ddb078444..c4dd6a738 100644
--- a/src/utils/src/export-map-html.ts
+++ b/src/utils/src/export-map-html.ts
@@ -1,7 +1,22 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {EXPORT_HTML_MAP_MODES} from '@kepler.gl/constants';
+import {EXPORT_HTML_MAP_MODES, KEPLER_GL_VERSION} from '@kepler.gl/constants';
+
+// React (and react-dom) no longer publish UMD builds starting with v19, so the
+// exported map loads React and the other UMD peer dependencies as ES modules
+// from an ESM CDN (esm.sh) via an import map, and exposes them on `window` as
+// the globals (React, ReactDOM, Redux, ReactRedux, styled) that the kepler.gl
+// UMD bundle and the inline scripts below expect.
+// See: https://react.dev/blog/2024/04/25/react-19-upgrade-guide#umd-builds-removed
+const REACT_VERSION = '19.1.0';
+const REACT_DOM_VERSION = '19.1.0';
+const REDUX_VERSION = '5.0.1';
+const REACT_REDUX_VERSION = '9.3.0';
+const STYLED_COMPONENTS_VERSION = '6.1.19';
+// es-module-shims lets the exported map keep working as a standalone file://
+// document (native ES modules/import maps are blocked under the file:// origin).
+const ES_MODULE_SHIMS_VERSION = '2.8.1';
/**
* This method is used to create an html file which will inlcude kepler and map data
@@ -11,8 +26,7 @@ import {EXPORT_HTML_MAP_MODES} from '@kepler.gl/constants';
* @param {Object} options.config this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}
* @param {string} version which version of Kepler.gl to load.
*/
-// TODO: revert to KEPLER_GL_VERSION once the React 19 release is published to npm with a UMD bundle
-export const exportMapToHTML = (options, version = '3.3.0-alpha.1') => {
+export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {
return `
<!DOCTYPE html>
<html>
@@ -48,16 +62,101 @@ export const exportMapToHTML = (options, version = '3.3.0-alpha.1') => {
<meta name="twitter:description" content="Kepler.gl is a powerful web-based geospatial data analysis tool. Built on a high performance rendering engine and designed for large-scale data sets.">
<meta name="twitter:image" content="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/kepler.gl-meta-tag.png" />
- <!-- Load React/Redux -->
- <script src="https://unpkg.com/[email protected]/umd/react.production.min.js" crossorigin></script>
- <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" crossorigin></script>
- <script src="https://unpkg.com/[email protected]/dist/redux.js" crossorigin></script>
- <script src="https://unpkg.com/[email protected]/dist/react-redux.min.js" crossorigin></script>
- <script src="https://unpkg.com/[email protected]/dist/styled-components.min.js" crossorigin></script>
+ <!--
+ Load React/Redux and the other UMD peer dependencies as ES modules.
+ React >= 19 no longer ships UMD builds, so we pull everything from an
+ ESM CDN (esm.sh) and re-expose them on window as the globals that the
+ kepler.gl UMD bundle (and the inline scripts below) expect.
+
+ IMPORTANT: this file must keep working as a standalone file, i.e. opened
+ directly from disk via the file:// protocol. Native ES module scripts
+ are always fetched with CORS semantics and a file:// document has an
+ opaque (null) origin, so the browser refuses to load native modules or
+ import maps locally. To keep the standalone-file behaviour we run
+ es-module-shims in "shim mode" (importmap-shim / module-shim tags): it
+ is a classic script (loads fine from file://) that resolves the import
+ map and executes the modules as blob: URLs, sidestepping that
+ restriction. The import map pins a single React instance and uses
+ external= so react-redux / styled-components reuse it (otherwise React
+ hooks break).
+ -->
+ <script>
+ // Trigger es-module-shims "shim mode" so it always parses the
+ // importmap-shim / module-shim tags below instead of deferring to the
+ // native loader (which fails under file://).
+ window.esmsInitOptions = {shimMode: true, version: '${ES_MODULE_SHIMS_VERSION}'};
+ </script>
+ <script async src="https://ga.jspm.io/npm:es-module-shims@${ES_MODULE_SHIMS_VERSION}/dist/es-module-shims.js" crossorigin="anonymous"></script>
+
+ <script type="importmap-shim">
+ {
+ "imports": {
+ "react": "https://esm.sh/react@${REACT_VERSION}",
+ "react/jsx-runtime": "https://esm.sh/react@${REACT_VERSION}/jsx-runtime",
+ "react-dom": "https://esm.sh/react-dom@${REACT_DOM_VERSION}?external=react",
+ "react-dom/client": "https://esm.sh/react-dom@${REACT_DOM_VERSION}/client?external=react",
+ "redux": "https://esm.sh/redux@${REDUX_VERSION}",
+ "react-redux": "https://esm.sh/react-redux@${REACT_REDUX_VERSION}?external=react,react-dom,redux",
+ "styled-components": "https://esm.sh/styled-components@${STYLED_COMPONENTS_VERSION}?external=react,react-dom"
+ }
+ }
+ </script>
+
+ <!--
+ Expose the ES modules as globals for the UMD kepler.gl bundle, then load
+ the kepler.gl UMD script and the app bootstrap script only after those
+ globals are available. The kepler.gl UMD bundle is a classic script
+ (which loads fine from file://), so it is injected dynamically here once
+ the globals are in place to guarantee the correct ordering.
+ -->
+ <script type="module-shim">
+ import * as React from 'react';
+ import * as ReactDOM from 'react-dom';
+ import * as ReactDOMClient from 'react-dom/client';
+ import * as Redux from 'redux';
+ import * as ReactRedux from 'react-redux';
+ import * as StyledComponents from 'styled-components';
- <!-- Load Kepler.gl -->
- <script src="https://unpkg.com/kepler.gl@${version}/umd/keplergl.min.js" crossorigin></script>
+ // esm.sh namespaces expose the module's default export under .default.
+ // Normalize so the globals match the shape the React 18 UMD builds had:
+ // - React / Redux / ReactRedux keep their full namespace (named exports).
+ // - ReactDOM merges the classic + client entry so both createPortal and
+ // createRoot are available (createRoot moved to react-dom/client in v19).
+ // - styled-components' global must be the callable default (styled) with
+ // its named exports (ThemeProvider, withTheme, css, keyframes, ...)
+ // attached, since the kepler.gl bundle relies on both.
+ window.React = React.default || React;
+ window.ReactDOM = Object.assign({}, ReactDOM.default || ReactDOM, ReactDOMClient);
+ window.Redux = Redux.default || Redux;
+ window.ReactRedux = ReactRedux.default || ReactRedux;
+ window.styled = Object.assign(StyledComponents.default, StyledComponents);
+ function loadScript(src) {
+ return new Promise(function(resolve, reject) {
+ var script = document.createElement('script');
+ script.src = src;
+ script.crossOrigin = 'anonymous';
+ script.onload = resolve;
+ script.onerror = reject;
+ document.head.appendChild(script);
+ });
+ }
+
+ // Load the kepler.gl UMD bundle after the globals are in place, then run
+ // the app bootstrap scripts (marked as type="text/kepler-bootstrap").
+ loadScript('https://unpkg.com/kepler.gl@${version}/umd/keplergl.min.js')
+ .then(function() {
+ var bootstraps = document.querySelectorAll('script[type="text/kepler-bootstrap"]');
+ bootstraps.forEach(function(node) {
+ var script = document.createElement('script');
+ script.text = node.textContent;
+ document.body.appendChild(script);
+ });
+ })
+ .catch(function(error) {
+ console.error('kepler.gl: failed to load UMD bundle', error);
+ });
+ </script>
<style type="text/css">
body {margin: 0; padding: 0; overflow: hidden;}
</style>
@@ -73,8 +172,8 @@ export const exportMapToHTML = (options, version = '3.3.0-alpha.1') => {
/**
* Provide your MapBox Token
**/
- const MAPBOX_TOKEN = '${options.mapboxApiAccessToken || 'PROVIDE_MAPBOX_TOKEN'}';
- const WARNING_MESSAGE = 'Please Provide a Mapbox Token in order to use Kepler.gl. Edit this file and fill out MAPBOX_TOKEN with your access key';
+ window.MAPBOX_TOKEN = '${options.mapboxApiAccessToken || 'PROVIDE_MAPBOX_TOKEN'}';
+ window.WARNING_MESSAGE = 'Please Provide a Mapbox Token in order to use Kepler.gl. Edit this file and fill out MAPBOX_TOKEN with your access key';
</script>
<!-- GA: Delete this as you wish, However to pat ourselves on the back, we only track anonymous pageview to understand how many people are using kepler.gl. -->
@@ -85,10 +184,10 @@ export const exportMapToHTML = (options, version = '3.3.0-alpha.1') => {
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-64694404-19', {
'storage': 'none',
- 'clientId': localStorage.getItem('ga:clientId')
+ 'clientId': (function(){try{return localStorage.getItem('ga:clientId')}catch(e){return null}})()
});
ga(function(tracker) {
- localStorage.setItem('ga:clientId', tracker.get('clientId'));
+ try{localStorage.setItem('ga:clientId', tracker.get('clientId'));}catch(e){}
});
ga('set', 'checkProtocolTask', null); // Disable file protocol checking.
ga('set', 'checkStorageTask', null); // Disable cookie storage checking.
@@ -103,8 +202,12 @@ export const exportMapToHTML = (options, version = '3.3.0-alpha.1') => {
<!-- Kepler.gl map will be placed here-->
</div>
- <!-- Load our React component. -->
- <script>
+ <!--
+ Load our React component. This script is not executed inline: it is run
+ by the module shim in <head> once the kepler.gl UMD bundle (and its
+ global peer dependencies) have finished loading.
+ -->
+ <script type="text/kepler-bootstrap">
/* Validate Mapbox Token */
if ((MAPBOX_TOKEN || '') === '' || MAPBOX_TOKEN === 'PROVIDE_MAPBOX_TOKEN') {
alert(WARNING_MESSAGE);
@@ -285,9 +388,7 @@ export const exportMapToHTML = (options, version = '3.3.0-alpha.1') => {
const root = reactDOM.createRoot(container);
root.render(app);
}(React, ReactDOM, app));
- </script>
- <!-- The next script will show how to interact directly with Kepler map store -->
- <script>
+
/**
* Customize map.
* In the following section you can use the store object to dispatch Kepler.gl actions