nx with vite builds a lib with peer dependencies (react, react-dom)

1.1k Views Asked by At

I've a standard installation: nx with vite as bundler. I have a main app and a library. Both uses react. Also a library can be used independenly. I'm trying to build library with a command:

nx build --production <library-name>

but I see that react and react-dom exist in the built bundle. There are two package.json files: root and library. In both files react and react-dom are set as peerDependencies.

At the beginning react and react-dom were devDependencies. By the way, the were packed into production build. I moved them into peerDependencies. It didn't help, they are still packed into production build.

How to explain vite that they should not be included into production bundle for my library?

1

There are 1 best solutions below

0
alexahdp On

I think I've found a solution. The problem was in vite.config.js. At the beginning I added "react" and "react-dom" into rollupOptions.external:

export default defineConfig({
  ...
  build: {
    rollupOptions: {
      external: ["react", "react-dom"],
    }
  }
})

After that react and react-dom were excluded from production build, but other react-libraries on which react depends were still there.

Then I found another solution - rollup-plugin-peer-deps-external:

import peerDepsExternal from 'rollup-plugin-peer-deps-external';

export default defineConfig({
  plugins: [
    peerDepsExternal(),
    ...
  ]
})

It helped. Now production build for a library doesn't contain react or react-dom or its dependencies