Skip to content

Bundlephobia API hooks and components

May 11, 2020


Want to access npm package details in your app without setting up your own server and tracking? Easily use the bundlephobia API.


Bundlephobia is an amazingly wonderful site that lets us know how big bundles are before using them.

https://bundlephobia.com/

"🏋️ find the cost of adding a npm package to your bundle" https://github.com/pastelsky/bundlephobia

While it's not much publicized, there's an API exposed to get some details for a given package:

https://bundlephobia.com/api/size?package=<package-name>

For example, the latest version of react-query returns the following values: https://bundlephobia.com/api/size?package=react-query:

{
  "assets": [
    {
      "gzip": 6104,
      "name": "main",
      "size": 19909,
      "type": "js"
    }
  ],
  "dependencyCount": 2,
  "dependencySizes": [
    {
      "approximateSize": 31288,
      "name": "react-query"
    }
  ],
  "description": "Hooks for managing, caching and syncing asynchronous and remote data in React",
  "gzip": 6104,
  "hasJSModule": "dist/react-query.mjs",
  "hasJSNext": false,
  "hasSideEffects": false,
  "name": "react-query",
  "peerDependencies": ["react"],
  "repository": "https://github.com/tannerlinsley/react-query.git",
  "scoped": false,
  "size": 19909,
  "version": "1.3.4"
}

As you can tell, we can get some useful details from this API 🤯!

You may be predicting the next step 💡, but I thought it would be helpful to create a component to show these details for a given package, with up-to-date details. Enter bundlephobia-inline, <BundlephobiaInline />, and useBundlephobia()!

import BundlephobiaInline from "bundlephobia-inline";

<BundlephobiaInline packageName="react-query" />;

I like that! 🤩

What about other components?

The basic BundlephobiaInline component is super-opinionated and likely isn't what you'll want for every project. Instead, the bundlephobia-inline package also exposes the useBundlephobia hook for a wrapper around the bundlephobia API using react-query!

import { useBundlephobia } from "bundlephobia-inline";

With some simple tweaking, you can even configure .mdx files to render bundlephobia codeblocks using this<BundlephobiaInline /> component.

More on that in the next post...


Further reading...