如何解决Nextjs从父目录导入外部组件
我有外部目录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"),];
}
}
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'
我是否还需要在Webpack config.externals
中包含此目录?当前的nextjs webpack externals
-----
options.isServer: false
[ 'next' ]
-----
-----
options.isServer: true
[ [Function] ]
-----
这怎么办?谢谢您的帮助
解决方法
从 Next.js 10.1.2 开始,您可以在 next.config.js 中使用当前的 experimental externalDir
选项:
module.exports = {
experimental: {
externalDir: true,},};
请注意,要使 React 组件正常工作,我还必须将根 package.json 声明为 yarn workspace:
{
// ...
"private": true,"workspaces": ["next-js-directory"],// ...
}
,
试试这个
next.config.js
module.exports = {
webpack: function (config,{ defaultLoaders }) {
const resolvedBaseUrl = path.resolve(config.context,"../");
config.module.rules = [
...config.module.rules,{
test: /\.(tsx|ts|js|mjs|jsx)$/,include: [resolvedBaseUrl],use: defaultLoaders.babel,exclude: (excludePath) => {
return /node_modules/.test(excludePath);
},];
return config;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。