How to make a buildable publishable library with Nx that is framework agnostic for browser and node.js

Viewed 2768

I have a monorepo (Nx Workspace) that has many libraries that were generated with @nrwl/js. These libraries depend on each other. They are small utility libraries that I intend to publish on NPM as separate packages.

According to Nx docs:

@nrwl/js is particularly useful if you want to

  • Create framework agnostic, just plain TypeScript libraries within an existing Nx workspace (say to use in your React, Node or Angular app)
  • Publish TypeScript packages to NPM

Yet, I now realize that the build command associated with @nrwl/js does not take into account a library's dependencies on other libraries in order to include them as peerDependencies into its publishable package.json. It also looks like it is making just a simple commonjs build that would be compatible with node.js but not with browsers.

I know that @nrwl/angular takes care of all that stuff for you when you build a library with it if you had marked it as publishable. My question is how do I get the same behavior but for a library that is not meant for Angular but for general purpose Javascript use in any framework or environment.

It's still early in development so if a solution to my problem would involve regenerating the libs using some other Nx generator, it wouldn't be too much of a hassle for me to do so, and I'd consider it.

Edit

I have since changed the build executor to @nrwl/node, which has the buildable and publishable options and behave the way I need.

I believe that @nrwl/js will eventually gain that ability but as of 2022-01-05 it didn't have it. For now, someone looking to publish libraries on NPM probably should use @nrwl/node to generate his new library projects and not @nrwl/js

1 Answers

If you want to publish a NPM package as a "universal package" to be consumed by Node.js and the browser, you would need to build it as UMD, to cover most consumer environments.

Though modern browsers support ES modules (import and export), you might need extra setup steps to consume them.

Related