JavaScript – Build and Transpilate Tutorial Using Latest Webpack in 2021

Webpack is a script bundler. It actually bundles the JS code into smaller, fast and compatible code. Compatible means the code will work in every browser consistently. JavaScript and ES6 is spreading its scope day by day but Browsers are not catching up. That is why your webpage may break on certain browsers. 

Using webpack is very easy. We have to create a folder naming new_js. Then we have to run this command. 

npm init

After pressing enter a few times we will have packages.json file in our new_js folder. Please paste this code in packages.js

{
  "name": "new_js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack --watch",
    "serve": "webpack serve --output-public-path=/",
    "dev": "webpack-dev-server --config ./webpack.config.js --hot"

  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.15.8",
    "@babel/plugin-transform-runtime": "^7.15.8",
    "@babel/preset-env": "^7.15.8",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.2.3",
    "babel-preset-env": "^1.7.0",
    "webpack": "^5.59.1",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.3.1"
  },
  "dependencies": {
    "@babel/polyfill": "^7.12.1"
  }
}

Now please run this command in the new_js folder.

npm install 

After completing this you will make a new file in the new_js folder naming webpack.config.js and paste this code. 

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
    },
    mode: 'development',
    devServer: {
        static : {
            directory : path.join(__dirname, "/dist/")
        }, 
        port: 9000
  } 
};

Now create a folder in the new_js directory called src and create a new file in there called index.js. This index.js file in which your JavaScript code will be written and transpiled to /dist/main.js.

Now run this command in the new_js in the command line. 

npx webpack

This will create dist folder in the new_js. Now create index.html in the dist folder and paste this code. 

<html>
    <head>
        <title>JS Transpile</title>
    </head>
    <body>
        <h1>JS Transpile</h1>
        <script src="main.js"></script>
    </body>
</html>

Now run this command in the command line. 

npx webpack-dev-server

Now run enter this URL in http://localhost:9000/ in browser and press enter. If you make changes in index.js and save, it will automatically reflect your changes on the server without refresh.