首页 > 解决方案 > Nextjs 从父目录导入外部组件

问题描述

我有外部目录common,我想将该目录中的反应组件导入web-static. 在web-static我使用nextjs。

在此处输入图像描述

目前我有这个错误:

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

我将这些行添加到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")
};

我的tsconfig.json文件:

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

Webpack 可以解析这些组件,但无法解析这些组件中已安装的包。

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

我是否需要将此目录也包含在 webpacks 中config.externals?当前的 nextjs webpackexternals

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

怎么可能做到这一点?谢谢你的帮助

标签: javascriptreactjswebpacknext.jsvercel

解决方案


从 Next.js 10.1.2 开始,您可以在 next.config.js 中使用当前实验 externalDir选项:

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

请注意,要使 React 组件正常工作,我还必须将根package.json声明为yarn 工作区

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

推荐阅读