Create JavaScript Library using Webpack and Babel

Write your own javascript library using webpack and babel

Let’s create our own webpack configuration bundle a small JavaScript utility library using webpack and babel.

Setting up the Source code:

We will be creating two utility functions into two separate files in our source folder.

Step 1: Create a directory demo and run the following command in it

The following command will create a package.json in your project root. I am using a -y to initialize it with the default option:

$ npm init -y

Create a directory structure that looks like this:

demo
 | — src/
 | — package.json

Step 2: Adding our source code

Add source code into src directory :

src
 | — index.js
 | — capital.js
 | — addDOMContent.js

Utility library contains two functions capital and to capitalize a string addDOMContent, to add content to a web page, each in its own module.

capital.js:

function capital(string) {
const capitalizedString =
string.substring(0, 1).toUpperCase() + string.substring(1)
return capitalizedString
}

export default capital

addDOMContent.js:

function addDOMContent(content) {
const node = document.createElement("h1")
node.innerText = content
document.body.appendChild(node)
}

export default addDOMContent

Inside our index.js, we will import these two functions.

index.js:

import capital from "./capital"
import addDOMContent from "./addDOMContent"

export { capital, addDOMContent }

We got this source code ready but we need to bundle it so that the browsers can understand. Anyway, as a responsible developer, we are going to do that 😄.

Step 3: Install some project dependency as they are needed during development

$ npm i --save-dev webpack webpack-cli @babel/core @babel/preset-env babel-loader

We need webpack to bundle our code and webpack-cli is a command-line tool that uses webpack to do the same. It also requires babel-loader to transpile our ES6 code to ES5 before bundle to support some past version of browsers. Then it will help to create our own Javascript library.

Step 4: Webpack and babel configuration

Create a webpack.config.js at the root of the project.

webpack.config.js:

const path = require("path")

module.exports = {
entry: path.resolve(__dirname, "src/index.js"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "index_bundle.js",
library: "$",
libraryTarget: "umd",
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: "babel-loader",
},
],
},
mode: "development",
}

More understanding of webpack configuration. Let’s discuss this:

  • entry: Webpack to know where to start, it needs an entry point to our app.
  • module.rules: Each file in Node is treated as a module. Webpack itself understands only JavaScript and JSON modules. Since we want to transpile ES6, we need a babel-loader and webpack need 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. library and library targets are used to expose our library where the library being the name,$ here, and library target is the property to configure, how the library will be exposed. Here we will be using UMD.
  • mode: Webpack bundles code into either development mode or in production mode.

Create a .babelrc file:

{
presets: ["@babel/preset-env"]
}

@babel/preset-env javaScript without any polyfills and syntax transforms .babel-loader uses babel under the game.

New project structure:

demo
|-- src
| |-- index.js
| |-- capital.js
| |-- addDOMContent.js
|-- webpack.config.js
|-- .babelrc
|-- package.json
|-- node_modules

Step 5: Bundle package.json file

We already added our source files and add an npm script to build final code using webpack and modify main property inside our package.json to point it to a bundled code.

package.json

{
"name": "demo",
"version": "1.0.0",
"description": "",
+ "main": "dist/index_bundle.js",
+ "scripts": {
+ "build": "webpack"
+ },
"keywords": [],
"author": "Sunanda",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"@babel/core": "^7.10.4",
"@babel/preset-env": "^7.11.0",
"babel-loader": "^8.1.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
}
}

The main property in package.json is a direction to the entry point of the module.

Finally, we created our utility library using ES6!

Run this command to generate the bundled code to use:

$ npm run build

Time to test our library

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Demo</title>
</head>
<body>
<script src="dist/index_bundle.js"></script>
<script>
console.log($)
alert($.capital("SUNANDA"))
$.addDOMContent("Well It Works Fine!!!")
</script>
</body>
</html>

Save it and run it on your browser, you will see the name capitalized.

I hope you enjoyed this article. Let us know your query as a response.

Leave a Reply

Your email address will not be published.