【问题标题】:Dynamically import all component sub directories without using full path不使用完整路径动态导入所有组件子目录
【发布时间】:2017-05-24 12:07:59
【问题描述】:

我正在为 React 使用 Next.js。我喜欢 Arc(其他反应样板)如何动态导入组件而无需开发人员指定路径。

import { Input, Label, Field, HomePage, PageTemplate } from 'components' 

文件夹结构可能看起来像这样:

components
|_ index.js
|_ atoms
  |_ Input
  |__ index.js
|_ molecules
|_ organisms
|_ templates

我想像这样导入它:

import { Input } from 'components'

用于动态导入的代码:components/index.js

const req = require.context('.', true, /\.\/[^/]+\/[^/]+\/index\.js$/)

req.keys().forEach((key) => {
  const componentName = key.replace(/^.+\/([^/]+)\/index\.js/, '$1')
  module.exports[componentName] = req(key).default
})

但是它不起作用。我得到的错误:

找不到模块:错误:无法解析模块“组件”...

问题是require.context 在服务器端不可用。 我想我需要在加载器配置中指定要像这样导入的路径。任何人都可以分享如何正确完成此操作的提示吗?

【问题讨论】:

  • 为什么不让你的 /components/index.js 导出文件夹中的所有组件?
  • @Robsonsjre 能否请您链接参考或显示示例?顺便说一句,这在后台如何工作?它会破坏性能或内存消耗吗? Next.js 默认做 SSR,只渲染导入的内容。

标签: javascript reactjs webpack next.js


【解决方案1】:

我认为没有一种简单可靠的方法可以用 Next.js 做你想做的事

标准/“正确”的答案是使用相对路径来导入本地组件。它有点样板,但我认为你最终会发现它比使用 Next.js 让它以 Arc 方式做事要少。


跟进@Robsonsjre 的建议:

为什么不让你的 /components/index.js 导出文件夹中的所有组件?

我认为有一个隐含的“你编写那个 index.js 文件”。对于您的示例,它看起来像这样:

export {default as Input } from './atoms/Input';
export {default as Foo } from './molecules/Foo';
// etc

问题是您必须记住每次添加或删除组件时都更新此文件。这可能是可以自动化的,但我不知道有任何系统可以做到这一点。

【讨论】:

  • 我目前的解决方法是放弃原子设计并将我的所有组件放入同一个文件夹中。但是,我在 babel 文件中添加了别名。所以我可以从'~redux/input/actions`中导入import MyComponent from '~components/MyComponent' or import {myAction}之类的东西
【解决方案2】:

这种方式并不完全是您想要的,但工作方式相似,性能良好,因为它只有指向导入组件的对象指针

//Input.js
class Input extends Component {
  render() {
   return <div>'input'</div>
  }
}
export default Input

//index.js
export { default as Input } from './Input/Input'

//otherComponent.js
import { Input } from './components' //path to folder components

【讨论】:

  • 似乎比使用香草方式添加更多步骤而不是减少它
猜你喜欢
  • 2021-05-03
  • 2016-11-20
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 2011-11-23
  • 2014-04-18
  • 1970-01-01
  • 2020-01-12
相关资源
最近更新 更多