How to setup a React JS project from scratch (without Create React App) (React Router v6)

How to setup React project without create-react-app [ Best way to learn React environment] [react-router-dom v6]

Hello Friends! 🙏. React JS Tutorial we will setup React project without create-react-app command😎, this is the best way to learn React as we will setup react environment and will explore react project dependencies.

React JS project can be setup using only one command & it only takes few minutes🚀 . Everyone use it & while command does its magic, all sit relaxed on their chair enjoing whatsapp/Music… whatever… depends on your network speed🤣 . But in this tutorial, we will setup react project from scratch.

Chalo suru kiya jaye!🍻 Lets start! 🕺

Step 1: Install/Upgrade/Verify Node

To start with setup React project, first please verify if your machine has node v >= 14 & npm v >=5.6.
If not, then install node package here.

While upgrading node package on my machine to latest version: 16.13.1 which includes npm 8.1.2, I faced one issue, may be you also get this type of error, check here to resolve it: WARN npm does not support Node.js v16.13.1

Step 2: Initialize a folder

So friends! first thing we have to do is to create a blank folder 📁 & initialize it using below command

npm init

This command will run a wizard of questions/choices related to the project & we have to answer/select them. This basically creates a package.json file which will include all our answers/selections.

React JS,setup react project,react tutorial,configure webpack,configure babel,setup react project without create-react-app

Step 3: Adding React Project Dependencies

Adding React

To use React we need core react package that contains the functionality needed to define React components.
Then we need renderers like react-dom to render the app on the web browser, or react-native to render the app on iOS/Android environment.
In our case we need react-dom as we are building for the web browser.
And lastly react-router-dom to handle routing in the application , it contains DOM bindings for React Router.

As we have installed the latest react-router-dom package i.e. v6, there are many breaking changes. I got to know about these breaking changes when I got stuck in a issue: WARN export ‘Switch’ (imported as ‘Switch’) was not found in ‘react-router-dom’. So better read the v6 documentation before diving into it 😎.

npm install react react-dom react-router-dom

Adding Babel – JS Compiler

Babel is a compiler which converts ES6 code to ES5 code, so that older browser can also run the application.
So basically It lets us write modern JavaScript code that still works in older browsers.

npm install --save-dev @babel/core @babel/cli

babel/core contains the main babel functionality i.e. converting the modern JS to ES5.
babel/cli is used to run babel from command line using its inbuild commands

npm install --save-dev @babel/preset-env @babel/preset-react

These presets tells babel to target specific type of code, like in our case we want to convert ES6+ and JSX code to ES5 code which is needed for React project. We will use these presets while doing configurations later in this tutorial.

Adding Webpack – Bundler

Webpack is a bundler for modern JS projects, this basically combines all the modules used in the project to one or multiple bundles

npm install --save-dev webpack webpack-cli webpack-dev-server

webpack contains the core functionality and webpack-cli is to run webpack from command line.
webpack-dev-server is to view projet in browser locally while development.

By default Webpack process only JS files and to process other assest like images, CSS & HTML it requires loaders, below are some basic loaders:

npm install --save-dev babel-loader html-loader style-loader css-loader

babel-loader: loader for babel files
html-loader: loader for HTML files
css-loader: loader for CSS files
style-loader: loader to inject styles into DOM

Optional: To use CSS preprocessors like SCSS, you will have to install sass-loader.

npm install --save-dev sass-loader sass

By default Webpack bundles CSS into JS, to generate seperate CSS file, you will have to install mini-css-extract-plugin

npm install --save-dev mini-css-extract-plugin

Now we need a HTML page to inject all the files/bundles generated by Webpack. For that we need to add html-webpack-plugin.

npm install --save-dev html-webpack-plugin

Now our package.json file looks like this:

React JS,setup react project,react tutorial,configure webpack,configure babel,setup react project without create-react-app

That’s all in the dependencies 😅, lets jump to create an App then some configurations and then will try to run it 🕺.

Step 4: Creating ‘Hello World’ React App

Create src folder📁 and then create a component App.js in it.

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

const App = () => {
   return <div className="message">Hello, World!</div>;
};

export default App;

Now create a style for the App component styles.scss.

// src/styles.scss
.message {
    text-align: center;
    font-size: 30px;
}

Now we need to create the main entry file (index.js) which will render the app in a DOM element having id=”root“, this element we will create later in this tutorial. This rendering is done by react-dom.

// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Routes } from "react-router-dom";

import App from "./App.js";
import "./styles.scss";

const routing = (
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
    </Routes>
  </BrowserRouter>
);

ReactDOM.render(routing, document.getElementById("root"));

Step 5: Configure Webpack

Now we will have to configure webpack, webpack-dev-server, loaders and plugins that we installed above 😅, lets start!

Create a blank webpack configuration file webpack.config.js in the root folder and start adding the below configurations.

Below is the main configuration for webpack, here you have to give the entry point of the file (index.js in our case) and output path for the generated bundles (dist in our case). Empty configurations like devServer, rules, plugins, optimization will configure one by one below.

// /webpack.config.js
// imports
const path = require('path');

// module
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist')
  },
  devServer: {},
  rules: [],
  plugins: [],
  optimization: {}
};

Now we will configure loaders in module rules: [] defined above

Configure SCSS.

Note: Loaders are evaluated/executed from bottom to top.
Here execution starts with sass-loader, continues with css-loader and finally ends with style-loader.

{
  test:/\.scss$/,
  use: [{
      loader: 'style-loader'
    },
    {
      loader: 'css-loader'
    },
    {
      loader: 'sass-loader'
    }
  ]
}

Configure Babel

babel-loader configuration.
options.preset will tell babel to use these presets while compiling the code.

{
  test: /\.(js|jsx)$/,
  exclude: /(node_modules)/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: ["@babel/preset-env", "@babel/preset-react"],
    },
  }
}

html-loader configuration

{
  test: /\.html$/i,
  loader: "html-loader",
}

Configure plugins

mini-css-extract-plugin will extract the styles from bundle and generates a seperate file styles.css in the dist folder.
html-webpack-plugin will create html file at dist/index.html and will automatically inject all the webpack generated files along with the CSS gerenated by mini-css-extract-plugin.

// add in imports
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');

// add in plugins array
new MiniCssExtractPlugin(),
new HtmlWebpackPlugin({
  template:"./src/index.html"
})

// modify the CSS loader configuration
{
  test: /\.scss$/,
  use: [{
      loader: "style-loader"
    },
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        esModule: false,
      },
    },
    {
      loader: "css-loader"
    },
    {
      loader: "sass-loader"
    },
  ],
}

// update optimization property
optimization: {
  splitChunks: {
    cacheGroups: {
      styles: {
        name: "styles",
        type: "css/mini-extract",
        chunks: "all",
        enforce: true,
      },
    },
  },
}

Use of esModule: false in above configuration: while compiling the App I was getting some warnings related to mini-css-extract-plugin you can check that here: WARN export ‘default’ (imported as ‘content’) was not found .

For html-webpack-plugin we need to create a html template which will be used by this plugin to inject the scripts & styles generated by webpack. For tha create index.html file inside src folder 📁. This html will contain the element having id=”root“, this will be the element where app will load using react-dom.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello World App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Now configure webpack-dev-server. It needs directory which must be path to the dist folder and a port to run on. If you want webpack to open the App in browser automatically provide open: true.

devServer: {
  static: {
    directory: path.join(__dirname, 'dist'),
  },
  port: 9000,
  open: true
}

Check here the final webpack.config.js file.

Step 6: Adding build commands

To build or run the project we will have to add some commands in package.json file under scripts property.

"scripts": {
  "start": "webpack-dev-server",
  "build": "webpack"
}

start command will execute webpack-dev-server which will build the project in memory and load the page on the browser.
build command will build the project in dist folder with all the files.

Check here the final package.json file.

Now the final moment😅 🥳🥳

npm run start // to start the app in browser
npm run build // to generate the dist folder with files
React JS,setup react project,react tutorial,configure webpack,configure babel,setup react project without create-react-app

And in source view, you can see the injected JS and Style file.

React JS,setup react project,react tutorial,configure webpack,configure babel,setup react project without create-react-app

👉Checkout the project here.

Thats all in this React JS tutorial, here we learned how to setup react project without create-react-app and also covered how to configure webpack, configure babel, configure Webpack loaders and plugins, added build commands.

❓If you have any question or suggestion, please feel free to comment.

👉 Do you know we can setup React App inside a docker container, check here!

Thanks🙏.

Leave a Comment

Your email address will not be published.