这种 Next.JS 文件夹结构推荐吗?

98
我们已经采用了以下项目结构。
|- pages
    |- <page_name>
        |- index.js             # To do a default export of the main component
        |- MainComponent.jsx    # Contains other subcomponents
        |- main-component.css   # CSS for the main component
        |- OtherComponents.jsx  # more than 1 file for child components that are used only in that page
        |- __tests__            # Jest unit and snapshot tests
|- components
    |- index.js                 # Exports all the default components of each component as named exports
    |- CommonCmpnt1
        |- CommonCmpnt1.jsx
        |- common-cmpnt-1.css
        |- index.js             # To default export the component
        |- __tests__
    |- CommonCmpnt2
        |- CommonCmpnt2.jsx
        |- common-cmpnt-2.css
        |- index.js             # To default export the component
        |- __tests__

需要澄清的是,没有任何东西损坏了,它的工作非常出色。我们有一些组件在组件目录中被多个页面重复使用,导入方式如下:

// Assuming we are inside MainComponent.jsx
// ...
import { CommonCmpnt1 } from '../../components';    // We even take it a step further and use absolute imports

此外,仅使用一次的组件位于其 pages 文件夹中。

我们现在唯一面临的问题是热模块重新加载已经失效了,即每当我们编辑 pagescomponents 目录中的 .jsx 文件时,我们必须手动重新加载页面以查看更改(不影响 CSS 文件)。这是我们习惯了的事情,所以并没有对我们产生严重影响。

我的问题是,是否存在我们不知道的任何迫在眉睫的灾难?


4
下一个项目中肯定不会使用通用的CSS,他们将使用基于JavaScript的CSS,例如styled components - Code Maniac
@CodeManiac 我同意,但这更多是一种偏好而不是解决方案。我们在styled-jsx(样式组件),sasscss之间交替使用。 - cross19xx
12个回答

-2

我更喜欢将与该页面相关的组件放在该页面的文件夹下。而components文件夹仅用于共享组件。

您可以在next.config.js中自定义pageExtensions属性。

module.exports = {
  pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}

通过上述配置(也是官方示例中的配置),只有扩展名为.page.jsx的文件将被视为页面。

pages/
├─ about/
│   ├─ index.page.jsx
│   └─ components/
│       ├─ MainComponent/
│       │   └─ index.jsx
│       └─ FooComponent/
│           └─ index.jsx
│
├─ _app.page.jsx
├─ _document.page.jsx
└─ index.page.jsx

参考资料:next.config.js: 自定义页面扩展 | Next.js


-2

很可能没有一种确定的文件夹结构方式,这将完全取决于什么对您更方便。

这是我通常组织我的应用程序的方式

pages/
├─ assets/
│   ├─ images/
│   ├─ icons/
│   └─ misc/
├─ components/
│   ├─ Buttons/
│   ├─ Cards/
│   └─ ...
├─ config/
│   └─ config.ts         //configuration constants such as ip,keys etc
├─ constants/
├─ contexts/             // all your context files
├─ helpers/              // any extra functions
├─ hooks/                // for intricate react hooks
├─ interfaces/           // for typescript interfaces
├─ layouts/              // for all layout files
├─ modules/              // if you develop each module seperately
├─ pages/          
├─ services/             // for all your api calls
├─ styles/

将所有内容都添加到页面中,感觉不太对。 - hafiz ali
根级别可以改名为app/或类似的名称,否则看起来已经足够好了。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接