繁体   English   中英

next.js和webpack resolve.modules

[英]next.js and webpack resolve.modules

我正在使用next.js构建一个React应用,并且正在next.config.js文件中使用webpack配置。

具体来说,我想有使用的WebPack的更好进口resolve.modules配置。

但是,当我在next.config.js文件中添加以下行时:

config.resolve.modules .concat(['styles','static','components','imports'])

然后import FooBar from 'components/index/FooBar" (例如在pages/index.js文件中) import FooBar from 'components/index/FooBar" ,它仍然无法工作。 FooBar

该组件存在,并且如果使用相对路径,导入工作正常。 但是我想更好地导入,我知道webpack可以实现(例如,参见react-boilerplate )。

我在用webpack做错了吗? 也许这是一个真正的错误?

resolve.modules将查看为导入模块配置的目录。 因此,当导入components/index/FooBar ,它将显示在:

styles/components/index/FooBar
static/components/index/FooBar
components/components/index/FooBar
imports/components/index/FooBar

相对路径看起来更远,但这在这里无关紧要,并且路径保持不变,只是爬上了目录树(请参见resolve.modules )。

大概这些路径都不符合您的组件。 要获取component/index/FooBar您只需要导入index/FooBar

import FooBar from 'index/FooBar';

检查带有绝对导入NextJS示例

const path = require('path')

module.exports = {
   webpack (config, options) {
       config.resolve.alias['components'] = path.join(__dirname, 'components')
       return config
    }
}

或者,应通过将其添加到next.config.js文件中来工作:

config.resolve.modules.push(path.resolve('./'));

(并且不需要任何babel插件)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM