In this blog we will learn how to create our own webpack configuration to bundle a small JavaScript utility library using webpack and babel.
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.
demo
and run following command in it. $ npm init -y
The above command will create a package.json
in your project root. I am using a --y to initialize it with default options.
Directory Structure
demo
|-- src/
|-- package.json
Let’s add our source code into src
directory:
src
|--index.js
|--capital.js
|--addDOMContent.js
Our 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
function capital(string) {
return (capitalizedString =
string.substring(0, 1).toUpperCase() + string.substring(1))
}
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 }
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.
#javascript #es6 #programming