Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs import external components from parent directory

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

like image 819
kraizybone Avatar asked Aug 17 '20 12:08

kraizybone


People also ask

Where do components go in Nextjs?

📁 Creating custom files for components But it is advisable to create standalone files for components. Now, conventionally, components should be stored in the components directory at the root directory of the app. - components/Header.

What is dynamic import next JS?

Examples. Next. js supports lazy loading external libraries with import() and React components with next/dynamic . Deferred loading helps improve the initial loading performance by decreasing the amount of JavaScript necessary to render the page.

Does Next JS have a src folder?

The src directory is very common in many apps and Next. js supports it by default.


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"],
  // ...
}
like image 196
Pier-Luc Gendreau Avatar answered Oct 06 '22 07:10

Pier-Luc Gendreau