How to Create a React app from scratch using Webpack 4
Tags: webpack, javascript, react, webdev
Published: 2018-05-08 00:15:05

---
title: How to Create a React app from scratch using Webpack 4
published: true
description: Create a React app from scratch using Webpack 4
tags: webpack,javascript,react,webdev
cover_image: https://images.pexels.com/photos/7367/startup-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260
---



**How to create a React app from scratch
Using [Webpack4](https://webpack.js.org/).**

First, we need to create our app folder.

```
mkdir  reactscratch
cd     reactscratch
npm init // intializing package.json file
```

They are a lot of packages need  to install so that 

Open your package.json file and paste the below code and save it.

{% gist https://gist.github.com/saigowthamr/322cda6a96640d5b608843a728872d68  %}

Now in your terminal paste the below command so that project 
dependencies installed

```
npm i // i for install
```

I will explain later what these packages are doing.


Now create a webpack.config.js file in your directory. and paste below code

```
module.exports={
    entry:{
     index:'./src/index.js',
    },

  output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
      chunkFilename:'[id][hash].js',
      publicPath:'/'
    },
    
}
```
Because we need to tell the  webpack   entry point and output .

**entry Point**: The entry point is index.js so that it takes all 
                 required imports and exports from index.js and outputs 
                 it in the dist folder naming bundle.js file.


But webpack does more it takes code from the index.js and applies some
transformations, for example, converting es6 to es5.


Now let's add our transformations  to our webpack config file

``` 
module: {
        rules: [

          {
            test: /\.(js|jsx)$/,
            exclude: /(node_modules|bower_components)/,
            use:['babel-loader']

          }
    ]
}
```

**What above code does is it checks if any file ends with .js/.jsx 
send that files to the babel-loader and apply transformations.**

Like we are using jsx but our browser doesn't understand jsx so that
babel loader takes our jsx and converted it into javascript.


They are different types of loaders avaiable css-loader style-loader file-loader ,html-loader. 

We can add more loaders in rules array now I'm showing how to  add css-loader

```
  {
            test:/\.css$/, use:[
           {loader:"css-loader",
              options:{
                minimize:true,
                sourceMap:true
              }
   }
```

**css-loader**: goes through possible @import and url() lookups within the matched files and creates source map for our CSS files, compress the css files by removing white spaces.


Webpack offers us  plugins  they are different types of plugins
available.

let's use plugins now 

```
 new MiniCssExtractPlugin({
      filename: "[name]-[hash].css",
      chunkFilename: "[id][hash].css"
    })
```

This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.

[name]:it indicates the name of the css file we created in our projected.
[hash]:webpack adds some random hash code.


Now you have some understanding about what webpack does

This is our final webpack.config.js file

{%  gist https://gist.github.com/saigowthamr/06130a4b529508a9e175331a8b76283c %}

With these our webpack custom setup is completed.

**But we are not created any js/html/css yet.**

![](https://thepracticaldev.s3.amazonaws.com/i/17o8r5kgrrrnt0cvahvm.png)

I'm using the above folder structure.

Create the index.html  file  in public folder

{% gist https://gist.github.com/saigowthamr/12b55350abcc7658478589c639b5b63e  %}


In our web pack config file, we are already pointing to this HTML file.

![](https://thepracticaldev.s3.amazonaws.com/i/0vnwcjirl2h1cicnf31b.png)

**Template**: We are entering the path where our HTML file is located.
**inject**: it is optional actually what it does is Inject the script files inside the body tag.


In src folder, we can create react components now

for example **app.js**

```
import React from 'react';
import './app.css';
import img from '../public/assets/download.png'

class App extends React.Component{
    render(){
        return(
            <div className="app">
             <h1>Hello React</h1>
               <img src={img} className="img"/>

            </div>
        )
    }
}
export default App;
```

Let's create an index.js file now in src folder why  because we are  using entry point as index.js in our webpack config file.

```
import React from 'react';
import ReactDom from 'react-dom';
import App from './app';

ReactDom.render(<App/>,document.getElementById('root'))
```


**npm start** // to run the  webpack development server 

![](https://thepracticaldev.s3.amazonaws.com/i/x9tpjph3o3et17yc7h3y.png)

It should be something like above image.

###### If you need a  code for the  production run **npm run build**

webpack creates a dist folder with required files. 
![](https://thepracticaldev.s3.amazonaws.com/i/sup1o2tnossh46ikm7qw.png)


Now you have some great understanding about webpack and loaders.

If  you want to add routing and lazyloading I will be  will show it in my
next post


[**CODE REPOSITORY**](https://github.com/saigowthamr/React-app-Boilerplate).



## Resources

- [Webpack docs](https://webpack.js.org/concepts/)

- [Webpack Plugins](https://webpack.js.org/plugins/)

- [Webpack loaders](https://webpack.js.org/loaders/)

### If you want to know about react in lower level check out my post

[Explaining 🐘React like I don't know anything](https://dev.to/saigowthamr/reactjs-for-beginners-very-detailed-35k4)