[ad_1]

How to create a multi-page React app with multiple entry points using Create React App without ejecting it.

Create React App frameworks allow you to easily create single-page applications, but do not support multiple entry points. To give you an example, if a website generates separate homepages for mobile and desktop clients, the pages may be sharing some common React components with each other, so it may not be practical to create two completely separate React applications.

See also: Bundle React App with Gulp

CRA does not support multiple entry points, but there are two ways to resolve this issue.

option 1 Eject from the Create React application using the npm run eject command and update the entry inside webpack.config.js file to include multiple entry points.

Option 2 Use an alternative authoring tool such as Vite.js that includes support for multiple out-of-the-box input points.

Option 3 Use the wired application: Allows you to easily make small changes and tweaks to your default Webpack settings without ejecting the application.

Option 4 Use REACT_APP environment variables to specify the target component and then use the ES5 dynamic imports to load the corresponding application component, as shown in this example.


Reacts at various entry points

Multiple entry points for the Create React application

If you intend to use the Create React App settings without ejecting it, here is a simple solution that will help you define multiple entry points and the output will be grouped into separate folders.

Inside the src folder, create two components.


import React from "react";

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

export default Desktop;

import React from "react";

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

export default Mobile;

The default input file index.js it looks 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")
);

Then edit your package.json file and add commands, one for compilation purpose.

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *