webpack installation

Webpack and easy installation guide

What is webpack?

Webpack is an open-source javascript bundler which run multiple task at a time. It can compile html, scss, css and js. It makes compatible ES6 js code to all browsers with the help of babel. It is a npm package.

Why should I use webpack?

You have to use webpack to bundle all the codes. When you make a big project which have a lot of js, css, images files, weback makes easier to use by creating one bundle package.

You can easily make only one bundle.js file from all other separate js files or css files.

Webpack makes easier to manage the site.

Requirements:

You already have installed nodejs in your computer. To install nodejs to your computer. If you don’t have installed nodejs, please install from here
Check the nodejs version node -v

Installation guide:

  1. make a folder with any name like “webpack-learning”
  2. Go to folder, open terminal and write npm init -y and hit the enter. After completing this, you will see node-modules folder and package.json file
  3. To install webpack package, run this code on terminal npm install --save-dev webpack

After installing webpack, if you open package.json file, you will see this code.

{
  "name": "webpack-learning",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "webpack": "^4.7.0"
  }
}

We will edit this code from package.json file and save it.

  "scripts": {
    "start": "webpack --watch"
  }

Now to run the webpack, we can run this code npm run start

configuration of webpack:

You are almost ready to use webpack. Now you have to follow the steps to setup webpack with your project.

Create a folder named src or anything on root directory where node-modules folder has. You have to put your development files here.
Create a file webpack-config.js file to root to configure your webpack which will compile your html, css, scss, js to dist folder.

To configure webpack-config.js file, you need to follow these steps.
Webpack has only 4 simple steps.
1. Entry
2. Output
3. Loaders
4. Plugins

Open webpack-config.js and write these codes.

1. Entry

Entry is the file location which is used as root location of webpack dependency graph from where webpack will start the work. I have used app.js file within src folder.

module.exports = {
  entry: './src/app.js'
};
2. Output

Output is the folder where webpack will send the compiled code or assets.
Here is the code of output code

const path = require("path");
module.exports = {
    output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  }
};

After using entry and output code, the code will be like this

const path = require("path");
module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  }
};

Yahoo! We have completed two steps: entry and output. Using entry point, webpack will start work from there and using output, webpack will send the code on dist folder. For path we will import path from node-modules folder.

3. Loaders

Now we load html, css, scss, js, images and others from src folder to dist folder.

For loading css
You need to install css-loader and style-loader. You can write code on terminal npm i css-loader style-loader.
You will see, css-loader and style-loader npm added on package.json file like this

  "dependencies": {
    "css-loader": "^0.28.11",
    "style-loader": "^0.21.0"
  }

After installing css and style loaders, you need to configure this code.

module: {
    rules: [
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']

        }
    ]
  }

Total code will be like this

const path = require("path");

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  },
  module: {
    rules: [
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']

        }
    ]
  }
};

This css will compile within app.js file in the dist folder.
Now create an index.html file and write some code of html and call app.js from dist folder.
Now write some css code in style.css file on the src folder and import this style.css file to app.js file.

const path = require('path');

import styleCSS from './style.css';

For loading SCSS files to CSS
We already learned how to load css files. For loading scss files to css in the dist folder, we have to install sass-loader and node-sass package of npm. On terminal run this code npm i sass-loader node-sass.

Write this code the webpack.config.js file to configure.

  {
    test: /\.scss$/,
    use: ['style-loader', 'css-loader', 'sass-loader']
  }

Now write some scss code in the style.scss file and import the style.scss file to app.js file like this.

import styleSCSS from './style.scss';

For loading JS file with babel
We can compile css and scss file. Now we will learn how to compile js file and how to use babel for ES6. Normal js code will compile automatically when you run webpack.
All js code will go to app.js file in the dist folder from src folder. For loading js with babel, we have to create another test. First we have to load babel-loader for babel.
For loading bael npm install babel-loader babel-core babel-preset-env webpack

Lets create another test for .js

{
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['es2015']
        }
    }
}

We use es2015 for preset-env.

Here is the full module code to see.

module: {
    rules: [
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']

        },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['es2015']
        }
      }
    }
    ]
  }

We can write some es6 js code in app.js file to check whether babel-loader is working and not.
In the app.js file

const lists = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const result = lists.map(list => list).join('+');

console.log(result);

Now we will run webpack npm run start
After compile, we can open app.js file from dist folder and we can see the result at the end of this file.

Wow!! we have completed 3 steps, we have already loaded css, scss and js with babel.

Now the last step is plugins.

4. Plugins

We can start working with webpack without plugins but plugins will help us to understand , manage the code. We will discuss the use of some plugins.

html-webpack-plugin
Using this plugin, we can send our html file to dist folder. For this, we have to load html-webpack-plugin to node-modules folder. Install npm package npm i html-webpack-plugin --save-dev
Now, require the plugin file from node-modules folder to webpack.config.js file.
const htmlPlugin = require('html-webpack-plugin');
Then create a plugins option below the modules and active the plugin like this

plugins: [
    new htmlPlugin({
      filename: 'index.html',
      template: 'index.html'
    })
]

If you want to send more html files to dist folder, use this way:

  plugins: [
      new htmlPlugin({
        filename: 'index.html',
        template: 'index.html'
      }),
      new htmlPlugin({
        filename: 'another.html',
        template: 'another.html'
      })
  ]

File structure will be like this

├── dist
│   ├── app.js
│   ├── index.html
│   └── another.html
├── index.html
├── node_modules
├── package.json
├── another.html
├── src
│   ├── app.js
│   ├── style.css
│   └── style.scss
└── webpack.config.js

If we use this plugin, we don’t need link css or js file. These files will be linked automatically in the html file.

extract-text-webpack-plugin
Normally css is stored within app.js file of the dist folder. If we want to use as external style file, we should use this plugin to extract the css and scss. Firstly, run the code to install the plugin npm i extract-text-webpack-plugin --save-dev

import extract-text-webpack-plugin file from node-modules folder to webpack.config.js file.
const ExtractScss = require('extract-text-webpack-plugin');

Use this to plugin options.

  plugins: [
    new htmlPlugin({template: 'index.html'}),
    new ExtractScss('style.css')
  ]

For extracting scss, use this to modules

{
    test: /\.scss$/,
    use: ExtractScss.extract({
        fallback: 'style-loader',
        use: ['css-loader', {
            loader: 'sass-loader',
            options: {
                sourceMap: true,
                outputStyle: 'expanded'
            }
        }]
    })
}

For more plugins, you can visit here

These are the 4 steps to configure webpack.

Don’t forget to know me your feelings. You can motivate me to write about more topics

8 thoughts on “Webpack and easy installation guide”

  1. Wonderful goods from you, man. I have understand your stuff previous to and you’re just too excellent.
    I actually like what you’ve received right here, certainly like what you’re stating and the way in which
    in which you are saying it. You are making it enjoyable and you continue to care for to
    stay it smart. I can not wait to learn far more from you.

    That is actually a terrific website.
    +905323495077

    1. Thank you so much. I will finish this blog soon. I hope you can learn in details when it will be complete

  2. Woah! I’m really digging the template/theme of this website.

    It’s simple, yet effective. A lot of times it’s hard to get that
    “perfect balance” between superb usability and visual appeal.
    I must say that you’ve done a awesome job with this.
    Also, the blog loads super quick for me on Chrome. Excellent
    Blog!

Leave a Reply

Your email address will not be published. Required fields are marked *