Getting Started with Webpack — Part 1

Beginner’s guide to getting started with Webpack

Getting Started with Webpack — Part 1

Introduction

Welcome to a very beginner friendly blog to get started with Webpack with minimal code and least configuration jargons. We’ll start by setting up a basic project and getting familiar with the essentials.

Setting Up Your Project

Create a new folder for your project, I will name it webpack-starter and run the following command to quickly get started.

npm init -y

By the end of this starter project I will be making an API call to a fake store API and dumping the data on screen. As goal here is to get started with webpack and pay little attention to UI.

Now to get started install few dependencies which we will be needing in this project.

Installing Dependencies

npm install webpack

npm install — save-dev webpack-cli

Folder Structure and Code

Now let’s create two files ‘webpack.config.js* and **‘src/app.js’*

Current Folder Structure

The interesting thing about webpack is that it runs at minimum config too, for starter here is webpack config file and app.js code.

//webpack.config.js
module.exports = {
  mode: "development",
  entry: "./src/app.js",
};
//app.js
function printMessage(message) {
  console.log(message);
  calculatelength(message);
}

function calculatelength(message) {
  console.log("Length of the message:", message.length - 1);
}

printMessage("hello from webpack");

Running Webpack

Now if you head over to package.json file and add this script and , run “npm run start” in the terminal

//package.json

......
"scripts": {
    "start": "webpack"
  },
......

We will see a dist folder appearing with main.js which consist of some boilerplate code which might look more compressed and straight to the point if we use mode as production in the webpack config file.

// dist/main.js
(() => {
  var message;
  message = "hello from webpack";
  console.log(message);
  console.log("Length of the message:", 17);
})();

Conclusion

Now that we have done the basic configuration of webpack and successfully compiled a sample code to a production build, in the next part we will focus on getting a simple website up and running with product details being fetched from API.