nx
nx copied to clipboard
Can't build and publish a React library containing "use client"
- [ ] I'd be willing to implement this feature (contributing guide)
Description
Using the default @nx/react
library generator with either the rollup or vite bundler ( the two options allowed by the generator),
it is not currently possible to preserve "use client" directives that are needed for server components / Next JS app router when the library is built and published.
Building the library with rollup presents a warning that the directive was deliberately stripped out, and Vite does not warn you about anything but doesn't keep the directive in its output.
Motivation
In order to publish libraries for use in React that contain client components for use in a Next JS app router system, the library should include use client
directives where applicable. Nx should support these statements out-of-the-box and not strip them out on build.
Suggested Implementation
To be honest, I don't know why the default behaviour of the @nx/react
package is to bundle the library files together on build. This disagrees with the approach taken in the @nx/js
package where libraries are compiled from Typescript but are left unbundled, with the assumption that the consumer of the library will bring their own bundler. Pre-bundling the library seems unnecessary, and I'm not really sure how use client
directives are supposed to be maintained in a pre-bundled output.
Relevant Next JS doc for library authors: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#advice-for-library-authors
Discussion on Rollup repo about it https://github.com/rollup/rollup/issues/4699