How to export multiple library variants from a single NPM package

Viewed 279

I'm creating a node library that could be partially used in web browsers.

My current structure is something like:

package.json
lib/
    index.js
    node.js
    web.js
modules/
    some-function.js
    some-node-function.js
    some-web-function.js
    ...

"lib/index.js" is specified as "main" in package.json

I'm using each file inside lib/ to re-export functions from modules/ filtered by target (all/node/web)

And I would like to use it like this:

import fullLibrary from "my-library";
import {someFunction} from "my-library";

import webOnlyLibrary from "my-library/web";
import {someWebFunction} from "my-library/web";

import nodeOnlyLibrary from "my-library/node";
import {someNodeFunction} from "my-library/node";

BUT keeping index.js, node.js and web.js inside /lib!

Currently only the first two import statements work (because index.js is pointed from package.json).

I know that I could place those files in the root of the package and it would work as expected when importing, but I was wondering if there was a way to do the same while keeping the files in /lib for cleanness.

In any case, is this the recommended way to expose multiple variants of a same library from a single NPM package?

1 Answers

Just for anyone that is having similar questions regarding libraries structure and organization.

Back then I started working with monorepos using Lerna and Yarn Workspaces and I haven't regret it. I think this is the most efficient way to go in terms of modularity, readability, scalability and maintainability.

Specifically, the question code would be traduced into this:

import webOnlyLibrary from "@my-library/web";
import {someWebFunction} from "@my-library/web";

import nodeOnlyLibrary from "@my-library/node";
import {someNodeFunction} from "@my-library/node";
Related