How to Create React App with Multiple Entry Points

Hey, friends today I will teach you How to Create React App with Multiple Entry Points. The Create React App frameworks allows you to quickly create single-page applications, but it does not support multiple entry points. For example, if a website generates separate home pages for mobile and desktop clients, the pages may share some common React components, making it impractical to build two completely separate React applications..

How to Create React App with Multiple Entry Points

so let get started with today Code snippets. Getting different problems is altogether gives a very different experience. today the Code snippets I am going to share with you is How to Create React App with Multiple Entry Points.

Although CRA does not support multiple entry points, there are a few workarounds.

Option 1: Using the npm run eject command, eject from the Create React App and update the entry in the webpack.config.js file to include multiple entry points.

Option 2: Use a different build tool, such as Vite.js, which supports multiple entry points out of the box.

Option 3: Use the rewired app, which allows you to easily make changes and small tweaks to the default Webpack configuration without having to eject the app.

Option 4 As shown in this example, use REACT APP environment variables to specify the target component and then use ES5 dynamic imports to load the corresponding app component.

You might also like our trending code snippets

How to build a multi-page React application with multiple entry points using Create React App without ejecting.

React Multiple Entry Points

Multiple Entry Points for Create React App

If you want to use the Create React App configuration without ejecting it, here’s a quick workaround that will allow you to define multiple entry points and have the output bundled in separate folders.

Inside the src folder, create two components.

// ./src/Desktop.js
import React from "react";

const Desktop = () => {
  return <h1>For Desktop</h1>;
};

export default Desktop;
// ./src/Mobile.js
import React from "react";

const Mobile = () => {
  return <h1>For Mobile</h1>;
};

export default Mobile;

The default entry file index.js looks something like this:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

Next, edit your package.json file and add commands, one per build target.

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "build:mobile": "cp src/Mobile.js src/App.js && npm run build && mv build build-mobile",
    "build:desktop": "cp src/Desktop.js src/App.js && npm run build && mv build build-desktop"
  }

Run npm run build:mobile when the build target is mobile or npm run build:desktop for the desktop entry point.

Leave a Comment