Creating a React Project from Scratch

Author
By Darío Rivera
Posted On in React

While many developers use tools like Vite or Create React App to start a project, understanding how to configure React from scratch is essential for any professional architect. This process gives you full control over your build pipeline and a deeper understanding of how modern JavaScript works.

Initializing the Project

The first step in any Node.js project is creating the package.json file. This file will manage our dependencies and scripts. Open your terminal and run:

npm init -y

Note: Ensure that if "type": "module" or "type": "commonjs" was automatically added to your package.json, you remove it. This will prevent Webpack from being strict about modules. Otherwise, you'll need to specify the extension of your JS files to be either .cjs or .mjs in some cases.

Installing Dependencies

We need two types of dependencies: the React libraries themselves and the tools required to bundle and transpile our code (Webpack and Babel).

Run the following command to install the bundler:

npm install webpack webpack-cli --save-dev

Next, install React along with the Babel presets necessary to translate JSX into standard JavaScript:

npm install react react-dom @babel/core @babel/preset-env @babel/preset-react babel-loader --save-dev

The Webpack Configuration

Webpack needs to know how to process our files. We must create a webpack.config.js file in the root of our project to define the entry point, the output, and the rules for our loaders.

const path = require("path");

module.exports = {
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      }
    ]
  }
};

Creating the Application

Now, we create our entry file index.js. This is where we will use the createRoot API from React to render our component into the DOM.

import React from "react";
import { createRoot } from 'react-dom/client';

const App = () => {
  return <h1>This is a React Script!</h1>
}

const root = createRoot(document.getElementById("app"));
root.render(<App />);

Compiling the Code

Finally, we use Webpack to transform our source code into a single, optimized file located in the dist folder. Execute the following command in your terminal:

npx webpack

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.