Loading React with Require.js (AMD)


This tutorial goes over how to load a React app with Require.js (AMD).

We’ll be using vanilla JavaScript instead of JSX so transpilation won’t be necessary.

Prerequisites

To get started, create index.html:

<!-- index.html -->
<html>
  <body>
    <!-- container for rendered React element -->
    <div id="root"></div>

    <!-- Require.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>

    <!-- main script -->
    <script src="main.js"></script>
  </body>
</html>

Load React with Require.js

In main.js, you’ll need to load React and ReactDOM before rendering your element:

// main.js
requirejs.config({
  // module name mapped to CDN URL
  paths: {
    // Require.js appends `.js` extension for you
    react: 'https://unpkg.com/react@17/umd/react.production.min',
    'react-dom': 'https://unpkg.com/react-dom@17/umd/react-dom.production.min',
  },
});

// load the modules defined above
requirejs(['react', 'react-dom'], function (React, ReactDOM) {
  // now you can render your React elements
  ReactDOM.render(
    React.createElement('p', {}, 'Hello, AMD!'),
    document.getElementById('root')
  );
});

Demo

JSFiddle example:



Please support this site and join our Discord!