reactjsnext.jsazure-artifactspnpm

Issues with <Image /> and <Link /> from Next.js in a monorepo package (peerDependencies set)


I'm working on a monorepo project where I have multiple packages published to Azure Artifacts. For example:

my-organization/ui my-organization/utils The monorepo is structured and works well overall. However, I'm encountering an issue when using components that rely on or from Next.js.

When consuming my-organization/ui in a Next.js project and rendering a component that uses or , I get the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

It's worth noting that Next.js is properly listed under peerDependencies in my packages.

The only workaround that has worked for me so far is:

Installing the same version of Next.js in the consuming app. Adding my-organization/ui to the transpilePackages in the next.config.js file, like this:

const nextConfig = {
  transpilePackages: ['my-organization/ui'],
  // other config...
};

module.exports = nextConfig;

While this resolves the issue temporarily, I would like to know:

Why does this issue occur specifically for and despite Next.js being listed as a peerDependency? Is there a better way to fix this problem without having to add the package to transpilePackages or installing the same version of Next.js in the consuming project?

Any guidance or insights into this would be greatly appreciated!


Solution

  • It turned out that my organization's package setup was causing a lot of the problems. Specifically, some subpackages were tightly coupled with others, and during the build process, peerDependencies (like next) were being installed unexpectedly, leading to issues.

    What helped me was switching to "workspace:*" in the package.json of my subpackages. This made dependency resolution local to the workspace and significantly improved things. For example:

    "dependencies": {
      "some-subpackage": "workspace:*"
    }
    

    This approach reduces coupling and ensures the local packages are used during builds. However, I'm still facing some ERR_MODULE_NOT_FOUND issues, which seem to be related to module resolution or mixed module types (CommonJS vs ESM). It's not the full solution, but switching to "workspace:*" might help others facing similar problems!"