Search code examples
reactjsreact-contextes6-modulescommonjs

Main project imports .esm.mjs dependencies, component library imports cjs.js dependencies


Our main project uses a self-made component library which uses a peerDependency (react-hook-form). The main project also uses react-hook-form as a dependency.

When taking a look at the JS debugger, "react-hook-form" imports are resolved like this for main components : "./node_modules/react-hook-form/dist/index.esm.mjs"

But like this for components from external library : "./node_modules/react-hook-form/dist/index.cjs.js"

Since they don't match, contexts created in main projects can't be used from the component library, it always returns null.

We've tried to define "react-hook-form" as a peerDependency and as externals in webpack-configs, but nothing seems to work.

Any idea would be welcomed.


Solution

  • We've found a solution. The component library was actually built with commonJS, while the main project was built with esModules.

    We've had to do two things :

    • find a way to build the component library with esModules (usually done within webpack config file)
    • change "main" path in package.json from library component. In our case, our project was creating several output folders, one for each module type. We had to target the esm one