Nextjs import external components from parent directory

Viewed 3924

I have external directory common and I would like to import react components from that directory into web-static. In web-static I am using nextjs.

enter image description here

Currently I having this error:

Module not found: Can't resolve 'react' in '/Users/jakub/Sites/WORK/wilio-web-common/common/src/@vendor/atoms'

I added these lines to next.config.js:

const babeRule = config.module.rules[babelRuleIndex];
if (babeRule && babeRule.test) {
  babeRule.test = /\.(web\.)?(tsx|ts|js|mjs|jsx)$/;
  if (babeRule.include) {
    babeRule.include = [
      ...babeRule.include,
      resolve(__dirname, "../common/src/@vendor"),
    ];
  }
}
config.resolve.alias = {
  ...config.resolve.alias,
  "@vendor": resolve(__dirname, "../common/src/@vendor")
};

My tsconfig.json file:

"paths": {
  "@vendor/*": ["../common/src/@vendor/*"]
}

Webpack can resolve these components but can't resolve installed packages in these components.

../common/src/@vendor/atoms/Test.js
Module not found: Can't resolve 'react' in '/Users/user1/Sites/WORK/web-app/common/src/@vendor/atoms'

Do I need to include this directory also in webpacks config.externals? Current nextjs webpack externals

-----
options.isServer: false
[ 'next' ]
-----
-----
options.isServer: true
[ [Function] ]
-----

How can be this done? Thanks for any help

1 Answers

Starting in Next.js 10.1.2, you can use the currently experimental externalDir option in next.config.js:

module.exports = {
  experimental: {
    externalDir: true,
  },
};

Note that for React components to work, I also had to declare the root package.json as a yarn workspace:

{
  // ...
  "private": true,
  "workspaces": ["next-js-directory"],
  // ...
}
Related