Setting up React with Webpack & babel.

Setting up React with Webpack & babel.

Been the first time having to set up React application from scratch, I kind of have a mixed feeling about it but I was ready to learn new stuff. That's one of the reasons I will prefer this job to any other job, being able to make learning new stuff easy for me by highlighting the process to get the job done since my task is to set up the workflow for our application. Here are the steps it takes for me to set up a webpack for our React application:

Since I already have Node JS installed on my machine, I went straight to setting up the webpack by creating a folder that will be containing my React application files. You can make a folder by running the command line:

mkdir foldername        

You can learn the basics about using the command line [ CLI ] here as it will really help fasten your work rate and lots more.

So, while inside the new directory I created, I ran a command that creates package.json file for my application using the command below

npm init -y        

This generates a package.json file without asking any question, after running this command then I install the generate the file by manually providing all the necessary information about my application using the command below:

npm init        

Once this package is created, I went ahead to create an src (source) folder for my React application and create two files inside this folder using the command:

touch index.html index.js        

The command above creates two files named index.html and index.js at the same thing and these files are to be created in the src folder, you can cd into the src folder after creating it. I believe you should have known or learned about how to use CLI from the link I paste earlier or from other links by now, so let's go straight to the point.

Now the real work is getting started slowly, It is time to setup my html file with the below code:

<!DOCTYPE html
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <meta name="theme-color" content="#000000" />
        <title> Setting up webpack with code with mercy </title>
    </head>
    <body>
        <noscript>
            You need to enable JavaScript to run this app.
        </noscript>
        <div id="root">
            <!-- This div is where our app will run -->
        </div>
    </body>
</html>>        

Now, it is time to set up a webpack for my application by installing it through npm or yarn, depending on your choice...

npm i -D webpack webpack-cli webpack-dev-server         

Webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript, but it can transform front-end assets such as HTML, CSS, and images if the corresponding loaders are included. webpack takes modules with dependencies and generates static assets representing those modules.

Webpack CLI provides?a flexible set of commands for developers to increase speed when setting up a custom webpack project. As of webpack v4, webpack is not expecting a configuration file, but often developers want to create a more custom webpack configuration based on their use-cases and needs.

Webpack-dev-server?can be used to quickly develop an application. This is used to live reload the webpage so that we can view our changes without having to refresh the page manually every time change is made.

Once the packages have been installed, they should be visible inside the package.json as a devDependencies. Also, it is advisable to remove the caret from the version of the packages in order to let us do a manual update instead, so the new update doesn't break changes in our application.

It's time to create a new file for our application to configure our webpack using the following command;

touch webpack.config.js        

I went ahead and install the?path?package as a?devDependency?since we need to work with paths in our app. We wouldn't want to inject the index.js file inside the HTML file. By installing?html-webpack-plugin?to help us do that automatically.

npm i -D path html-webpack-plugin        

Time to add some content to our index.js file, add the below code inside the index.js file before we run our webpack.

 (function codewithmercy() 
      console.log('Hello World! Welcome Code With Mercy');
 }());        

Once this is done, try and run your webpack to see how it works, incase you are getting an error message saying script not found, here is how I fix mine:

Goto your package.json file, you will see something that looks like this:

"scripts": {
     "webpack": "webpack",
     "start": "webpack serve",
     "test": "echo\"Error: no test specified\" && exit 1"
}         

This way the webpack should run in case it wasn't working before. Webpack will automatically take the src/index.js file, compile it and output it to dist/main.js and minify the code. So, now we should be able to see a dist folder in your root directory which contains a file name main.js, and we can go ahead and start our application by running the command npm start. Now it is time to setup our webpack.config,js file with the following code below:


const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: path.join(__dirname, "src", "index.js"),
    output: { 
       path: path.join(__dirname, "build"), 
       filename: "index.bundle.js" 
    },
    mode: process.env.NODE_ENV || "development",
    resolve: { 
       modules: [path.resolve(__dirname, "src"), 
                "node_modules"] 
    },
    devServer: {
       static: {
          directory: path.join(__dirname, 'public'),
       },
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, "src", "index.html"),
        }),
    ],
};
        

Here is a brief explanation for the components in this file:

  • ?entry and output tell our server what has to be compiled and from where. Also tells the server where the compiled version should be outputted.
  • mode: this is the mode of our output, which is set to ‘development’ for now. Should be changed to 'production' when the app is built for production.
  • resolve: used so that we can import anything from the?src?folder in relative paths rather than the absolute ones, same goes for node_modules as well.
  • devServer: this tells the webpack-dev-server what files are needed to be served. Everything from our src folder needs to be served (outputted) in the browser.
  • plugins: here we set what plugins we need in our app. As of this moment, we only need the html-webpack-plugin which tells the server that the index.bundle.js should be injected (or added if you will) to our index.html file.

It's time to add react, and react-dom to our application as a dependency using the command:

npm i react react-dom --save        

Time to modify our index.js file a little bit by adding the below code:

import React from 'react';
import ReactDOM from 'react-dom';

const App= () => {
    return (
        <h1>
            Hello World
        </h1>
    );
}

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

If we run the server now, we will get an error message in our console for not having an appropriate loader for react. Let's add some babel packages to our application as a devDependencies.

npm install -D @babel/core @babel/node @babel/preset-env @babel/preset-react babel-loader        

  • @babel ?/core: used to compile?ES6?and above to?ES5.
  • @babel ?/preset-env: determines which transformations or plugins to use and polyfills (i.e it provides modern functionality on older browsers that do not natively support it) based on the browser matrix you want to support.
  • @babel ?/preset-react: compiles the React code into ES5 code.
  • babel-loader: a Webpack helper that transforms your JavaScript dependencies with Babel (i.e. will transform the import statements into required ones).

We'll need to install some styles to the project, as well as have the ability to display images on the webpage (Remove the sass-loader and node-sass if know you won't be working with SCSS files).

npm i -D style-loader css-loader sass-loader node-sass image-webpack-loader         

  • style-loader: will add styles to the DOM (injects a?style?tag inside the HTML file).
  • css-loader: lets us import CSS files in our project.
  • sass-loader: lets us import SCSS files in our project.
  • node-sass: compiles SCSS files into normal CSS files.
  • image-webpack-loader: lets us load images in our project.

Now we need to add babel configuration by creating a file name .babelrc in the root of our directory by adding the below lines to let?babel-loader?know what to use to compile the code.


{
    "presets": [
        "@babel/env",
        "@babel/react"
    ]
}
        

We also need to install some packages in order to import files into our application such as images and so on. We also need to add a plugin that let us add class properties in our classes. It will let us work with Object-Oriented Programming.

npm i -D file-loader @babel/plugin-proposal-class-properties        

After installing this, we need to make some changes inside of our webpack.config.js so that Webpack will now use Babel. We’ll also configure Webpack to listen for style files and we are going to change the require statements to import.


const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: path.join(__dirname, "src", "index.js"),
    output: { 
       path: path.join(__dirname, "build"), 
       filename: "index.bundle.js" 
    },
    mode: process.env.NODE_ENV || "development",
    resolve: { 
       modules: [path.resolve(__dirname, "src"), 
                "node_modules"] 
    },
    devServer: {
       static: {
          directory: path.join(__dirname, 'public'),
       },
    },
    module: {
        rules: [
            { 
                test: /\.(js|jsx)$/, 
                exclude: /node_modules/, 
                use: ["babel-loader"] 
            },
            {
                test: /\.(css|scss)$/,
                use: ["style-loader", "css-loader"],
            },
            { 
                test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
                use: ["file-loader"] 
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, "src", "index.html"),
        }),
    ],
};
        

We also need to add the babel/plugin-proposal-class-properties to our .babelrc file, here is how our file should now look.

{
    "presets": [
        "@babel/env",
        "@babel/react"
    ],
    "plugins": [
        "@babel/plugin-proposal-class-properties"
    ]
}        

Then you can run the webpack and start our application to test if it is working according to the way it is

npm run webpack

npm start        

Thanks for reading my article, I hope you are able to learn one or two things from this article. The purpose of posting this article is to share my growth and also see how I can help others learn from me.

Like, share, and comment for others to see. Thanks

要查看或添加评论,请登录

Afolabi Ridwan Damilare的更多文章

  • My HGN Internship Goals

    My HGN Internship Goals

    So, a few days ago I got my HNG internship which got me excited because I've been waiting for such an internship that…

  • Sound Effect Project

    Sound Effect Project

    Link - GitHub page: https://github.com/mercyharbo/sound-effect - Live-site: https://github.

  • Difference between Git & GitHub

    Difference between Git & GitHub

    On Monday night, I started learning Git & GitHub to make my coding life easier and work with teams easy by…

  • Form Wave Project

    Form Wave Project

    This is a project from the 50 projects 50 days course by Brad Traversy and Florin that I was gifted by an amazing…

社区洞察

其他会员也浏览了