DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Updated on

How to build js library with webpack 5

In this article, I will discuss how to set up webpack configuration for your js library in a way that:

  1. works with tree shaking, for your modern users
  2. is build with global scope polluting js file, that other users can directly load from their html

Package file

First of all, let's take care of your modern users. In package.json, besides library info we will have following fields:

{
  ...
  "main": "src/index.js",
  "type": "module",
  "scripts": {
    ....                                                                                                                                                                                                                                                                                        
    "build": "webpack"
  },                                                                                                                                                                                   
  ...
}
Enter fullscreen mode Exit fullscreen mode

we want to keep ourself to esmodules, that's why there is "type": "module". The "main": "src/index.js" informs clients' webpack what files use for imports - effectively ignoring anything build locally by us. This is as intended, because it's client's build that knows what parts of our library to leave, and what drops.

Source code

src/index.js is an entry point to our library:

export { helloWorld } from "./hello-world.js";
Enter fullscreen mode Exit fullscreen mode

it importing & exporting all methods that are meant for external use.

src/hello-world.js contains a simple demo method:

export function helloWorld() {
  console.log("hello world!");
}
Enter fullscreen mode Exit fullscreen mode

Build for legacy clients

For all the cases where the user of our library has no build on their own, we will build the library on our side. Those can be simple pages that just whose author just wants to drop some js & have methods available; or legacy pages full of this kind of js imports anyway. The webpack.config.js that allow us to achieve that:

export default {
  output: {
    library: {
      type: "umd",
      name: "sdk",
    },
    filename: "sdk.js",
  },
};
Enter fullscreen mode Exit fullscreen mode

output.library.type: "umd" sets the export type to universal module definition - modules that are able to work on matter the environment, most importantly in our case - as drop-in js files. output.library.name sets the content of our module to be published on window.sdk - the same as you find jquery methods on $.

Link

Summary

In this article, we have seen simple set up for building js library. If you are interested in the code, you can find it here: https://github.com/marcin-wosinek/webpack-sdk

And an example of how it's working is here: https://marcin-wosinek.github.io/webpack-sdk/

Top comments (0)