Why and How to Use Webpack and Babel with Vanilla JS
Tags: webdev, javascript, productivity
Published: 2022-02-28 12:55:03

---
title: Why and How to Use Webpack and Babel with Vanilla JS
published: true
date: 2022-02-28 11:00:26 UTC
tags: webdev, javascript, productivity
canonical_url: https://www.syncfusion.com/blogs/post/why-and-how-to-use-webpack-and-babel-with-vanilla-js.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdu8bqaxdv99txbzipwp.png
---

When developing web applications, there are instances where our code seems complex, heavy, and less maintainable. There can be repetitive and lengthy code and unused assets. These conditions can slow down application performance, reduce efficiency, and even make it hard for the browser to load content.

However, [Webpack](https://webpack.js.org/ "Webpack") and [Babel](https://babeljs.io/ "Babel") are great tools for effectively manipulating JavaScript, CSS, and other webpage assets to make them smooth and efficient.

In this article, let’s see about the Webpack and Babel tools and how to use them with [Vanilla JS](http://vanilla-js.com/ "Vanilla JS") projects.

## What Are Webpack and Babel?

Webpack and Babel are tools for developers that optimize JavaScript applications.

Webpack is a module bundler we can use to minify multiple files in a JavaScript project and increase the overall efficiency. A module bundler takes in all the assets and comes up with a single output file. This artefact can be imported into our HTML, making it a more lightweight project.

As for Babel, it is a syntax converter and a transpiler. There may be times you want your code to be compatible with all browsers and environments, including the older ones. In such instances, a great option to try out is Babel.

## Why Use Webpack and Babel with Vanilla JS?

A simple project with a small number of lines in the script file is fine on its own. But consider a situation where there are hundreds of lines of code within the script file. In such instances, we have to break the code into several files to make it much simpler to comprehend. Then, we can concatenate the files to get the same output by calling only one script file in the main file.

But this can be troublesome as we cannot determine the dependencies and the proper order on our own. So, for that, Webpack is an essential tool, as it analyses the files, creates a dependency graph, and bundles up the files in the best possible manner.

Then, Webpack recursively explores all the files and identifies the dependencies. After that, it generates the minified output file and removes unnecessary assets. The whole process makes our Vanilla JS project easier to maintain and more efficient.

Babel, in turn, translates the latest JavaScript code (ES6+) into older JavaScript code (ES5). This makes the code compatible with all browsers, even when you use the latest JavaScript version to code.

## Advantages of Using Webpack and Babel with Vanilla JS

- Removes unused and unnecessary assets from the code, making it cleaner.
- Makes the code compatible with all web browsers.
- Bundles up the assets and minifies the components, making it easier for the browsers to load content.
- Improves the maintainability.
- Generates a dependency graph based on the dependencies of the assets.

## How to Use Webpack and Babel with Vanilla JS

It might be a bit complex to set up Webpack and Babel in a project. So, let me guide you through using Webpack and Babel in a Vanilla JS project step by step.

### The Folder Structure

There is a specific folder structure to be followed when using Webpack and Babel in your project.

We need two separate folders, **dist** for the output files and **src** for the input files. You have to keep the **_index.html_** file inside the **dist** folder. Next to the **_index.html_** file, within that folder, the minified output file will be generated by Webpack.

Refer to the following screenshot for the folder structure.

![Folder structure for using Webpack and Babel in a project](https://www.syncfusion.com/blogs/wp-content/uploads/2022/02/Folder-structure-for-using-Webpack-and-Babel-in-a-project.png)

### Installing Packages

We can initialize the project with **_yarn init_** or **_npm init_** and add the required dependencies using one of the following commands.

```
// with yarn
yarn add webpack webpack-cli webpack-dev-server --dev
// with npm  
npm install webpack webpack-cli –save-dev
```

After installing the dependencies, create a file with the name **_webpack.config.js_** in the root folder and add the following code into that file.

```js
const path = require('path');

module.exports = { 
  "mode": "none", 
  "entry": "./src/index.js", 
  "output": { 
    "path": __dirname + '/dist', 
    "filename": "bundle.js" 
  },
  devServer: { 
    contentBase: path.join(__dirname, 'dist') 
  }
}
```

Enter the main JavaScript file as the **entry** in the previous code and set the **path** to where you want the output file to appear.

In the **_index.html_** file, attach the **_bundle.js_** file using the following command:

```
<script src="bundle.js">
```

And inside the **_package.json_** file, don’t forget to add the following script to run Webpack.

```js
"scripts":{ 
  "build" : "webpack watch", 
  "dev-server": "webpack serve --open"
}
```

Now, we can complete the implementation of the project and build to see the output. The re-bundling process is automatic and will take place every time you save after making a change.

### Style Sheets

When using Webpack, getting the styles to work is a bit different. This is because we first have to install style loaders and then import the CSS styles.

```
// npm
npm install --save-dev css-loader style-loader
// yarn  
yarn add –dev css-loader style-loader
```

Inside the **_webpack.config_** file, add the following piece of code to use the loaders we installed in the previous step.

```js
const path = require('path'); 

module.exports = { 
  "mode": "none", 
  "entry": "./src/index.js", 
  "output": { 
    "path": __dirname + '/dist', 
    "filename": "bundle.js" }, 
    devServer: { 
      contentBase: path.join(__dirname, 'dist') 
    }, 
    "module": { 
      "rules": [{ 
        "test": /\.css$/, 
        "use": [ "style-loader", 
                 "css-loader" 
        ]
      },] 
   }
};
```

We can now add our styles in CSS files and start the dev-server to see the output.

Now, we have reached the final step. We have to install the Babel dependencies and load them.

```
// npm
npm install --save-dev babel-loader @babel/core @babel/preset-env
// yarn  
yarn add babel-loader @babel/core @babel/preset-env –dev
```

To get the loaders working, update the **_webpack.config_** file just like in the style loaders, with babel-loaders.

```js
const path = require('path'); 

module.exports = { 
  "mode": "none", 
  "entry": "./src/index.js", 
  "output": { 
  "path": __dirname + '/dist', 
  "filename": "bundle.js" 
}, 
devtool: 'cheap-module-eval-source-map', 
devServer: { 
  contentBase: path.join(__dirname, 'dist') 
}, 
"module": { 
  "rules": [ { 
    "test": /\.css$/, 
    "use": ["style-loader", "css-loader"] 
  }, 
  { 
    "test": /\.js$/, 
    "exclude": /node_modules/, 
    "use": { 
      "loader": "babel-loader", 
      "options": { 
        "presets": ["@babel/preset-env",] 
      } 
    } 
  }, 
] }};,
```

And now you should have a JavaScript project together with Webpack and Babel support.

## Best Practices to Follow

Following best practices when using these tools is essential, because otherwise, setting up can get complex. Webpack and Babel are tools that have a set of prerequisites, like an accurate folder structure and the correct packages.

It is crucial to install the necessary loader when bundling assets such as CSS, fonts, images, etc. So, here are a few tips to make your experience with Webpack and Babel easier.

### Keep your code clean and stick to the specified folder structure.

You must follow the specified folder structure. For example, especially when using Webpack, the **_index.html_** file should be there with the output file inside the **dist** folder.

### Set “private”: true in package.json.

This is a best practice to follow to prevent your code from accidentally publishing.

### Use code-splitting for big bundles.

If the bundles are large, we can activate code splitting with optimization.splitChunks to chunk the bundle into several pieces. The recommended size of the Webpack bundle is 200KB maximum.

### Follow the standard methods and documentation.

There are separate documentations for Webpack and Babel. Both of them have step-by-step instructions on properly setting up these tools and using them for different file types. By referring to these, you can learn almost everything about Webpack and Babel, including plugins, loaders, and presets.

- [Webpack documentation](https://webpack.js.org/concepts/ "Webpack documentation")
- [Babel documentation](https://babeljs.io/docs/en/ "Babel documentation")

## Final Thoughts

This article discussed what Webpack and Babel are and how to use them in a Vanilla JavaScript project. We discussed the advantages of using them and where to use them, too. It is worth considering using these tools because they can make your application load faster and make it more maintainable.

I hope you have found this article useful. Thank you for reading!

The Syncfusion [JavaScript suite](https://www.syncfusion.com/javascript-ui-controls "JavaScript UI controls")will be the only suite you will ever need to build an application. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download the [FREE trial](https://www.syncfusion.com/downloads/essential-js2 "Free evaluation of the Syncfusion Essential Studio") and evaluate the controls today.

If you have any questions or comments, you can contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion support forum"), [support portal](https://support.syncfusion.com/ "Syncfusion support portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Pros and Cons of Using JavaScript Interop in Blazor](https://www.syncfusion.com/blogs/post/pros-and-cons-of-using-javascript-interop-in-blazor.aspx "Pros and Cons of Using JavaScript Interop in Blazor blog")
- [10 JavaScript Naming Conventions Every Developer Should Know](https://www.syncfusion.com/blogs/post/10-javascript-naming-conventions-every-developer-should-know.aspx "10 JavaScript Naming Conventions Every Developer Should Know blog")
- [How to Bulk Edit Columns in JavaScript DataGrid](https://www.syncfusion.com/blogs/post/bulk-edit-columns-in-javascript-datagrid.aspx "How to Bulk Edit Columns in JavaScript DataGrid blog")
- [Pure and Impure Functions in JavaScript: A Complete Guide](https://www.syncfusion.com/blogs/post/pure-and-impure-functions-in-javascript-a-complete-guide.aspx "Pure and Impure Functions in JavaScript: A Complete Guide blog")