Creating javascript library with webpack

Although Webpack is mostly used for compiling and building web applications, it can be used to create JavaScript libraries too. Let's create a new javascript library and publish it on npm.

Let's say we want create a es6 library for calculations called "calculator".

Initiate npm library

npm init
# OR
yarn init

Install Webpack

npm install --save-dev webpack webpack-cli

Write ./src/index.js

export function add (a, b) {
    return a + b;

export function subtract (a, b) {
    return a - b;

export function multiply (a, b) {
    return a * b;

export function divide (a, b) {
    return a / b;


const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'calculator.js',
    library: {
      name: 'calculator',
      type: 'umd',

Library type umd helps to import in both environments Browser, Nodejs.

Update package.json

  "main": "dist/calculator.js",
  "module": "src/index.js"

The key main refers to the standard from package.json, and module to a proposal to allow the JavaScript ecosystem upgrade to use ES2015 modules without breaking backwards compatibility.

You are ready with your initial library to publish on npm repository!

Build and Publish

Decide which files to add as part of published library.

Create .npmignore


Update package.json

  "scripts": {
    "build": "webpack"

Run npm run build to build your library. Run npm publish to publish it on npm repository.