Loading React with Require.js (AMD)


Most tutorials show how to build React apps with module bundlers like webpack.

In this tutorial, I’ll go over how to build a very simple React app with Require.js (AMD).

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

To get started, create index.html with the following:

<!-- 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.2/require.min.js"></script>

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

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/[email protected]/dist/react',
        'react-dom': 'https://unpkg.com/[email protected]/dist/react-dom'
    }
});

// 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')
    );
});

Check out this fiddle to see a working example: