Getting Started With Webpack For Modern Web Development Javascript & Nodejs

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Getting Started

Modern Web Development is all related to faster app load time, easier development and deployment across multiple platforms, dependency-free application where you all the needed code for the application to run as expected in one place ready, compressed and minified for production use all of those are brought by the javascript bundlers or compiles which can help you a lot during your app development either you are about to startup or even a small static website project all need from you to learn the new technology and master it from the ground.

Webpack is one of the best bundlers if it's not the best right now and most widely used by developers either for Web or Nodejs and many ECMAScript (javascript) are supported (ES6, ES7, ES8, ESNext..) and with the support of third-party plugins and loaders you can pretty much it with any framework, language or platform. 

For bundling your code you need to provide it with a specific configuration that matches your project structure and the used languages or frameworks, therefore, it has a lot of configuration schemes that can match different use cases, in this is tutorial we are just going to cover a very basic getting started configuration of how to export a basic config object and bundle your code.

Make sure to check more about Webpack and the configuration scheme on the Official Website.

Also, make sure to have Nodejs & Npm installed on your machine because it's required for the use Webpack and project setup, however, if you don't, Get it From Here.

Project Setup

You pretty much use it any project, but a certain way to organize and put all your directories and files is highly recommended to better use and easier debugging and development, here is my project structure:

--dist/  ///< the same as the public folder (hold the final compiled js/css and other asset files)
--src/  ///< Holds the source files of your project 
webpack.config.js ///< Where all the webpack configuration is going to live
package.json ///< The required dependencies after initializing the project with NPM 

First, let us initialize our project with NPM and Nodejs and install the Webpack dependencies so we can bundler our code properly.

#Open a Terminal and Run (or Cmd) (Make sure to cd to your project)
npm init 

You are going to get prompted for a couple of questions regarding your project like the name, the author and git repo just leave it as default if you are not familiar with it.

npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (test)
version: (1.0.0) 1.0.0
description: Webpack
entry point: (index.js) app.js
test command:
git repository:
keywords:
author: Islem Penywis
license: (ISC) MIT
About to write to C:\Source\Projects\Deep-Draft\test\package.json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "Webpack",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Islem Penywis",
  "license": "MIT"
}

Is this ok? (yes)

Press enter and your project should have a new file automatically created for you (package.json) this is the main file for any Nodejs project that holds a list of dependencies of the project.

let's install the dependencies.

npm install webpack webpack-cli css-loader style-loader extract-text-webpack-plugin@next --save-dev

The extract-text-Webpack-plugin gonna allow us to load and compile CSS, SASS files into a separate CSS file and we are installing the next version to be released cause there is a problem with the current versions at lease at the time of releasing this tutorial so make sure to get the right versions for you. 

Now you are ready to configure your Webpack bundle environment to fit your project needs, in this case, we are going to use a very basic configuration and try to explain every part of it.

Basic Configuration

The Basic way of how Webpack actually works, is you provide it with the javascript (or typescript) source code by specifying the entry point or main file that Webpack compiler will start reading from and all you other source files need to be linked into this main entry point file, so it will load them using a specific loader (either the standard or a custom loader depending on what languages or version you are writing it on) and bundle them into one small minified file that will be generated on the dist/ folder.

Open up webpack.config.js or create it if it doesn't exist.

//Require the Path Nodejs module
let path = require("path");
//Make sure to export the config object as default export 
module.exports = {
 entry: path.resolve("./app.ts"), ///< (takes a absolute path)
 target: "node", ///< either for nodejs or web
 mode: "development", ///< bundle it in development or production 
 output: {
     filename: "app.js", ///< the Final Output file name (All code will be there)
     path: path.resolve("./dist"), ///< Final bundle directory (takes a absolute path)
 },
 resolve: {
     extensions: [".js", ".jsx", ".json"] ///< what type of file extensions to compile (source file)
 },
}

As you can see the configuration is quite straightforward and easy to read and understand, first, you have to specify the entry point file or from where Webpack gonna start compiling, and the target to Nodejs or web also the bundle mode either development which gonna help you in development phase for debugging and finding errors/issues easily or the production which is designed for deployment and publishing the application for the outside world.

For the output you have to give it the final bundle file name and its directory, the directory needs to be an absolute path, therefore, we are using path.resolve method to get an absolute path by giving it a relative one.

and lastly we give it which source file extensions gonna be resolved and compiled into the final bundler, in this case, we only need .js, jsx for React and .json.

If you want to use a custom loader for a specific file type, let's say we wanna load .css files with the CSS-loader that we installed earlier.

...
module.exports = {
...
module: {
    rules: [{
        test: /\.css?$/, ///< test for file extension, if it matches then use specified loader 
        loader: "css-loader" 
    }
}
...

the module object specify a custom configuration for each module (for ex: javascript.js files) and apply that during bundling process, and the rules tell it how exactly which one to compile so it's an array of object each object has a test property that tests a specific Regular Expression against a module (source file) and applies the specified loader in case it matches it, we will see this more in-depth with plugins in the next video tutorials so stay tuned.

Bundling 

Now after all of this project setup and configurations and all the talking it's time to try to compile something with Webpack, let's say we have an app.js file in our root directory that represents the main entry point file that we have specified on the Webpack configuration and we are just going to be a console.log on it just for testing it.

/* app.js */
console.log("Hello from a webpack bundle");

To compile you have to run a terminal and make sure it's under the root directory of your project where all the Webpack configuration and project setup is in and run Webpack it will automatically recognize and find the configuration and use it by default for building your project starting from app.js 

webpack 

Wait until the bundling is complete, afterward take a look on the dist/ folder you should find an app.js bundle file, in case you tried to open up and take a look you won't be able to understand what is it about and what is on there but stay with me it's the right way to create browser/Nodejs supported javascript scripts, now run it using Nodejs.

node ./dist/app.js 

You should get the messaged logged to you back successfully, therefore the Webpack compiler is working fine and you are ready to dive more into deeper and more complicated configuration for your project.

Hello from a webpack bundle

Awesome.

 

What's Next

Now you know why Webpack or using a bundler is very important for Moder Apps Development or at least know how to setup a very basic configuration of bundling your startup project, you can know go and try to learn from official Webpack documentation to know more about plugins, loaders and custom module options and much more or you can wait for the next video tutorials where we are going to explain them in details.

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games