Should I include node modules in my library package?
P粉716228245
P粉716228245 2023-09-12 19:36:43
0
1
588

I am developing a React component library. This library is used by several internal NextJs projects.

For compatibility reasons with NextJs, this library will need to be converted to CommonJs at some point.

The problem is that some npm dependencies of my library don't handle CommonJS. This is the case, for example, with swiper.

So I have two choices:

  • I would either declare npm dependencies as peerDependency and then have each consumer of my library transpile them correctly. This makes my library packages lighter, but it creates a lot of configuration constraints in each project (e.g. for NextJs as well as Jest).
  • Or I include the npm dependency in my package, which seems to me an anti-pattern, but it allows me to expose CJS and MJS: consumers of my library have almost nothing to do.

I can also envision a mix of the two: I ignore managing all dependencies for CommonJs and ES modules, and transpose only those that are necessary.

what do you think?

P粉716228245
P粉716228245

reply all(1)
P粉647504283

We have the same situation - we have a Next.js application that relies on a core library with underlying ESM modules. However, I recommend not bundling your dependencies. Your downstream applications may have the same dependencies and now you end up loading them twice. And you may have encountered this issue with other 3rd party dependencies (with ESM dependencies). Just add them to the transpilePackages list in next.config.js: https://nextjs.org/docs/app/api-reference/ next-config-js/transpilePackages. We also use next/jest which also seems to get the configuration and seems to work. The only caveat is that I found out that we have to transpile @babel/runtime but only when jest is running, otherwise it will break the main application.

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['@acme/ui', 'lodash-es'],
}
 
module.exports = nextConfig
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template