在(Vue,React)中导出带有子模块的模块的最佳方法是什么

What is the best way to export modules with submodules in (Vue, React)

使用 index.js 导出包含子模块的模块的最佳方法是什么。很长一段时间以来,我都遵循一种模式来命名和保存我的项目(Vue 或 React)中的 Web 组件。但我想要一种更实用的方法来使用单个索引导出模块以避免出现以下情况:

我的模式

import PostDetail from 'src/views/posts/PostDetail'

这是一个有趣的问题。一段时间以来,我一直在思考同样的问题,并尝试了几种不同的方法,最后选择了一种似乎对我来说效果很好的方法。

  1. 将您的可重用组件放在一个地方。
  2. 将使用可重用组件的布局包装器放在一个地方。

1.可重复使用的组件

您所有的可重用组件都包括自定义按钮和独立组件,如您提到的 Posts。如果您的帖子可以有详细信息和评论,请保留两个单独的组件 PostDetailsPostComments 并将它们导入并组合在一个单独的 Post 组件中。 即插即用是关键。。你可以在这里选择两种结构,

components/PostDetails

components/PostComments

components/Post

components/Post/PostDetails/...

components/Post/PostComments/...

并将它们导入 components/Post/Post.js

但是您的默认导出将在 components/Post/index.js 中,这将导出 Post.js。通过这种方式,您可以确保 Post 组件是组合的和可重用的,并且可以在任何 page/layout.

中作为 components/Post 导入

2。布局包装器

你所有的 pages/layouts 都在这里。典型的例子是主页,关于将导入组件并将它们放在正确位置的页面。

这通常与文件夹名称类似,例如页面或容器,具体取决于项目。

pages/home

pages/about

我有一些代码库可以帮助你更好地掌握这个项目结构。

Portfolio

React-Redux Boilerplate

我的应用程序使用 reactredux。我们主要尝试在代码文件夹结构上遵循模块化设计。

模块本身恰好是独立的,可以单独使用。如果模块的某些部分需要在模块本身之外使用,我们只通过它公开这些文件 index.js

以下是我们关注的内容:

Project-name
├── assets
│   ├── images
│   └── stylesheets
│       ├── components
│       ├── misc
│       ├── objects
│       └── vendor
├── build
│   ├── javascripts
│   └── stylesheets
├── src
│   ├── modules
│   │   │  
│   │   ├── common
│   │   │   ├── actions
│   │   │   ├── components
│   │   │   ├── helpers
│   │   │   └── reducers
│   │   ├── module_1
│   │   │   ├── sub_module_1
│   │   │   │   ├── actions
│   │   │   │   ├── components
│   │   │   │   │   └── body
│   │   │   │   ├── helpers
│   │   │   │   └── reducers
│   │   │   └── sub_module_2
│   │   │       ├── actions
│   │   │       ├── components
│   │   │       ├── helpers
│   │   │       └── reducers
│   │   ├── module_2
│   │   │   └── components
│   │   ├── module_3
│   │   │   ├── actions
│   │   │   ├── components
│   │   │   │   └── body
│   │   │   ├── helpers
│   │   │   └── reducers
│   │   └── module_4
│   │       ├── components
│   │       └── helpers
│   └── pages
├── stories
│   ├── common
│   ├── establishment
│   │   └── visiting_clinics
│   ├── providers
│   │   └── body
│   └── relations
└── tools

每个模块在其根目录下都有一个 index.js,它公开了将在其他模块中使用的所需文件和函数。

这种结构使本地文件交互变得顺畅,因为 imports 简短、清晰可见并且名称空间(基于功能)来自它的来源。