Exercise: Webpack


Idea: Introduction to Webpack.
Background: What is Webpack

What is Webpack?
Webpack is a tool to build JavaScript modules in your application. Webpack simplifies your workflow by quickly constructing a dependency graph of your application and bundling them in the right order. webpack can be configured to customise optimisations to your code, to split vendor/css/js code for production, run a development server that hot-reloads your code without page refresh and many such cool features.


webpack

In this exercise you will have to do a simple test of webpack in 4 steps:


Todo


Step 1

Create a new folder: "js-modules" in your VSCode project folder.
Start VSCode and open the new folder.
Open an integrated terminal window in VSCode: view->Integrated Terminal
Execute: npm init

Name: the new project should have the name: "js-modules" (type return)
Version: just use the default version (type return).
Description: Type a description (eg. "a simple test of js-modules and webpack").
Entry point: Use the default: "index.js" (type return)
Test command: non (type return)
Git repository: non (type return)
Keyword: non (type return)
Author: your name
License: (type return)
Ok? (type return)

Notice: a new file "package.json" is created (inspect)

Step 2
Create a new folder src
Create two new files in the src folder: index.js and sum.js


pupose

sum.js
This file should have a function sum that takes to arguments and return the sum. Make an export declaration to the function:

sum


index.js
This file should import the sum fuction ("require" in commonjs).
Call the function and send the result to the console:

index


Step 3
Install Webpack globally by running:
npm install webpack -g
Verify that it works by running
webpack -v

(Normally we dont recomment to install webpack globally, but for the use in this exercise/course its okay).

Configuration of Webpack:
Create a new file: "webpack.config.js"
The file should have a config-object with a property: "entry" with the value: "./src/index.js" (the entry-point) and a property: "output" with values for path and filename for the output file.
Notice: we are using the "path" module to help with resolving the path for the output-file (instead of using a absolut-path specification).
Export the config-object.

config


Now we are ready to run webpack and build the bundle.js file:


run


Step 4
In the terminal window run webpack by typing "webpack" and click return
Webpack create a new folder: "build" and a new file: "bundle.js"
Verify!

Now we a ready to test the result.
Create a new file: "index.html", add:

"<html><head><script src="../build/bundle.js"></script></head><body><h1>Test modules</h1></body></html>"

html

Browse the file, and use Chromes developertool (F12) to check the result (see console)


Enjoy ;-) / Henrik H