Nextjs 从父目录导入外部组件

kra*_*one 2 javascript reactjs webpack next.js vercel

我有外部目录common,我想将该目录中的 react 组件导入到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"),
    ];
  }
}
Run Code Online (Sandbox Code Playgroud)
config.resolve.alias = {
  ...config.resolve.alias,
  "@vendor": resolve(__dirname, "../common/src/@vendor")
};
Run Code Online (Sandbox Code Playgroud)

我的tsconfig.json文件:

"paths": {
  "@vendor/*": ["../common/src/@vendor/*"]
}
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

我还需要在 webpacks 中包含这个目录config.externals吗?当前的 nextjs webpackexternals

-----
options.isServer: false
[ 'next' ]
-----
-----
options.isServer: true
[ [Function] ]
-----
Run Code Online (Sandbox Code Playgroud)

如何做到这一点?谢谢你的帮助

Pie*_*eau 5

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

module.exports = {
  experimental: {
    externalDir: true,
  },
};
Run Code Online (Sandbox Code Playgroud)

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

{
  // ...
  "private": true,
  "workspaces": ["next-js-directory"],
  // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这不需要将工作区添加到我的 package.json 中就可以工作 (3认同)