user18941960
user18941960

Reputation: 55

How can I modify React build to give me multiple JavaScript files?

I have a multi-page application that doesn't use Node. It has a bunch of HTML and JavaScript files. I want to render React components in the application, which I found I am able to do with ReactDOM.render.

However, I am building out the React components separately in a project made with npx create-react-app. I can use npm run build which gives me a main.js file that contains a production ready version of all my components.

I can add this main.js file into my HTML files with a script tag to have my components render in my multi-page application.

However, the problem is that I notice when I run npm build, I get one main.js file that contains everything. This is not good because the app will run too slow if I have to load all of my React components in main.js file every time I go to a new page.

Instead, I am looking to only load the specific components I need for a page.

Example:

Let's say I had a test1 component and a test2 component. Page1 has a script to use test1, so I only want to load test1 on Page1. Page2 has a script to use test2, so I only want to load test2 on Page2. Therefore, I need a test1.js file and a test2.js file after npm run build

How would I do this?

Upvotes: 0

Views: 2126

Answers (1)

Wojtek
Wojtek

Reputation: 439

Sounds like a use case for Code Splitting.

If you want to split per-page with React Router you can do the following:

import React from "react";
import { render } from "react-dom";
import {
  BrowserRouter,
  Routes,
  Route,
} from "react-router-dom";

const Home = React.lazy(() => import("./Home"));
const Contact = React.lazy(() => import("./Contact"));

render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/contact" element={<Contact />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById("root")
);

This should generate multiple JS files for different components (e.g. pages) when used with some standard build tools like create-react-app.

Upvotes: 1

Related Questions