Loads React with native browser ESM resolution and Babel.
This repository shows the minimum configuration necessary to load React and React DOM directly into the browser without using a bundler. This also loads the React preset to support JSX.
npm install
npm start
> react-babel-esm@1.0.0 test /home/tbranyen/git/react-babel-esm
> bserve
Listening at http://127.0.0.1:8000
babel.config.js
bserve is a Babel http server, which behaves like @babel/cli, and automatically reads the .babelrc and babel.config.js files. You would most likely use the latter since it opts you into node_modules parsing, which is used here.
The @babel/preset-react preset is used to handle the defaults required by React applications and supports JSX.
The two required plugins are:
- babel-plugin-transform-commonjs Converts CommonJS to ESM.
- babel-plugin-bare-import-rewrite Forked to make compatible with the CommonJS plugin. Converts bare specifiers to node path resolution.
module.exports = {
presets: ['@babel/preset-react'],
plugins: [
'babel-plugin-transform-commonjs',
'@tbranyen/babel-plugin-bare-import-rewrite',
]
};
index.js
Unfortunately, React does not export named identifiers, so we are limited to
default imports for React and ReactDOM. Importing env.js allows setting the
process
global ahead-of-time.
import './env.js';
import React from 'react';
import ReactDOM from 'react-dom';
const { main } = window;
function App() {
const [ count, setCount ] = React.useState(0);
return <>
<div>Hello world, button clicked {count} times.</div>
<button onClick={() => setCount(count + 1)} children="Click" />
</>;
}
ReactDOM.render(<App />, main);
env.js
Allows opting into a specific environment.
const env = {
NODE_ENV: 'development',
};
window.process = { env };