In this blog we will learn how to create our own webpack configuration to bundle a small JavaScript utility library using webpack and babel.
This blog will be divided into two parts:
- Part I will be about setting up the source code.
- Part II will be about setting up the webpack and babel configuration and testing our library.
Let's create the source code for our library. For that we will be create two utility functions into two separate files in our source folder.
Step 1 : Create a directory demo and run following command in it.
1$ npm init -yThe above command will create a package.json in your project root. I am using a --y to initialize it with default options.
Directory Structure
1demo
2 |-- src/
3 |-- package.jsonStep 2: Adding our source code.
Let's add our source code into src directory:
1src
2 |--index.js
3 |--capital.js
4 |--addDOMContent.jsOur utility library contains two functions capital, to capitalize a string and addDOMContent, to add content to a web page, each in it's own module.
capital.js
1function capital(string) {
2 const capitalizedString =
3 string.substring(0, 1).toUpperCase() + string.substring(1)
4 return capitalizedString
5}
6export default capitaladdDOMContent.js
1function addDOMContent(content) {
2 const node = document.createElement("h1")
3 node.innerText = content
4 document.body.appendChild(node)
5}
6export default addDOMContentInside our index.js, we will import these two functions.
index.js
1import capital from "./capital"
2import addDOMContent from "./addDOMContent"
3export { capital, addDOMContent }So far we got the source code ready but we still need to bundle it so that the browsers can understand and oh boy!, we need to support some older browsers too 🙄. Anyway, being responsible developers we are going to do that 😎.
Step 3: Let's install some of our project dev dependencies as they are only needed during development.
1$ npm i --save-dev webpack webpack-cli @babel/core @babel/preset-env babel-loaderWe need webpack to bundle our code and webpack-cli is a command-line tool that uses webpack to do the same. Also webpack requires babel-loader to transpile our ES6 code to ES5 before bundling (Remember, what I said about being responsible developers 😃).
Step 4: Now let's get our webpack and babel configuration in place. (We are almost there)
4.1. Create a webpack.config.js at the root of the project.
webpack.config.js
1const path = require("path")
2module.exports = {
3entry: path.resolve(__dirname, "src/index.js"),
4output: {
5path: path.resolve(__dirname, "dist"),
6filename: "index_bundle.js",
7library: "$",
8libraryTarget: "umd",
9},
10module: {
11rules: [
12{
13test: /.(js)$/,
14exclude: /node_modules/,
15use: "babel-loader",
16},
17],
18},
19mode: "development",
20}There are a couple of things we need to understand about webpack configuration. Stay with me for a couple more minutes.
-
entry: In order for webpack to know where to start with, it needs to know the entry point to our app. -
module.rules: Each file inNodeis treated like a module. Webpack itself understands only Javascript and JSON modules. Since we want to transpile ES6, we needbabel-loaderand webpack needs to know the rules on how to process the Javascript using the given loader. -
output: After creating the bundle, webpack needs to know what name to give it and where to put it.libraryandlibraryTargetare used to expose our library wherelibrarybeing the name,$here andlibraryTargetis the property to configure, how the library will be exposed. Here we will be using UMD. UMD is a module system capable of working everywhere, be it in the client, on the server or elsewhere. -
mode: Webpack bundles code into either development mode (unminified) or in production(minified) mode. I am using a hard coded value here for the demo. You can set it using environment variables too.
4.2. Create a
.babelrcfile at the root of the project.
.babelrc
1{
2 presets: ["@babel/preset-env"]
3}@babel/preset-env let's us use the latest Javascript without any polyfills and syntax transforms.babel-loader uses babel under the hood.
By Now our Project Structure should look like this:
1demo
2|-- src
3| |-- index.js
4| |-- capital.js
5| |-- addDOMContent.js
6|-- webpack.config.js
7|-- .babelrc
8|-- package.json
9|-- node_modulesStep 5: One last step. I know I keep saying that but I promise this is last 😬.
We have added our source files, now let's add an npm script to build final code using webpack and modify the main property inside our package.json to point it to our bundled code.
package.json
1{
2 "name": "demo",
3 "version": "1.0.0",
4 "description": "",
5+ "main": "dist/index_bundle.js",
6+ "scripts": {
7+ "build": "webpack"
8+ },
9 "keywords": [],
10 "author": "Hridayesh Sharma",
11 "license": "ISC",
12 "dependencies": {},
13 "devDependencies": {
14 "@babel/core": "^7.10.4",
15 "@babel/preset-env": "^7.11.0",
16 "babel-loader": "^8.1.0",
17 "webpack": "^4.44.1",
18 "webpack-cli": "^3.3.12",
19 }
20}In package.json the main property is a direction to the entry point of the module that the package.json is describing.
Hurray! We have finally created our utility library using ES6.🥳
Run $npm run build to generate the bundled code and use it in the next step.
Let's test our library now.
index.html
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Demo</title>
7 </head>
8 <body>
9 <script src="dist/index_bundle.js"></script>
10 <script>
11 console.log($)
12 alert($.capital("hridayesh"))
13 $.addDOMContent("Well It Works Fine!!!")
14 </script>
15 </body>
16</html>Save it and run it in your browser. You will see the name capitalized.
The complete code is available at LoginRadius Engineering Blog Sample Repo
Thanks for reading the blog. For detailed information and execution example of this blog, please refer to the video below:

