Nextjs 从父目录导入外部组件 [英] Nextjs import external components from parent directory

查看:47
本文介绍了Nextjs 从父目录导入外部组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

目前我有这个错误:

找不到模块:无法解析/Users/jakub/Sites/WORK/wilio-web-common/common/src/@vendor/atoms"中的react"

我将这些行添加到 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 可以解析这些组件,但无法解析这些组件中安装的包.

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'

我是否需要在 webpacks config.externals 中也包含这个目录?当前的 nextjs webpack externals

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

推荐答案

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

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

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

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

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"],
  // ...
}

这篇关于Nextjs 从父目录导入外部组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆