Skip to content

tbranyen/react-babel-esm

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Using React with ESM

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.

Install the dependencies

npm install

Start the server

npm start
> react-babel-esm@1.0.0 test /home/tbranyen/git/react-babel-esm
> bserve

Listening at http://127.0.0.1:8000

Visit http://127.0.0.1:8000

Source code

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:

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 };

About

Using React and Hooks without a bundler, from npm, and with native browser ESM

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published