0

I like a modular architecture and I'd love to have something like:

/pages
--/somepage
----/index.tsx
----/_components
------/ComponentA.tsx
------/ComponentB.tsx

Rather than having a folder outside of /pages where I keep all of the components for /somepage organized.

However, I understand the /pages folder is treated differently. Are there any performance implications or reasons why I should not do this?

user12457151
  • 853
  • 2
  • 12
  • 25
  • 1
    [if you setup Next.js custom page extension config, it will work as expected](https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions). If you don't, every file will become a route, which you may NOT want – boop_the_snoot Aug 31 '22 at 18:25
  • Does this answer your question: [Can't build React/Next project - found page without a React Component as default export](https://stackoverflow.com/questions/65598753/cant-build-react-next-project-found-page-without-a-react-component-as-default)? – juliomalves Sep 04 '22 at 11:28

1 Answers1

1

Every file in pages/ is treated as a real route in your application. For example, in your example, someone could visit mysite.com/somepage/_components/ComponentA as a real page.

If you want this behavior, go for it. If you don't, put your components outside of the folder.

As for performance implications, Next.js will compile/build your components files as pages, too, which will probably slow down the build process needlessly.

So please don't do this:

/pages
--/somepage
----/index.tsx
----/_components
------/ComponentA.tsx
------/ComponentB.tsx

and do this:

/components
--/somepage
----/ComponentA.tsx
----/ComponentB.tsx
/pages
--/somepage
----/index.tsx
kelsny
  • 23,009
  • 3
  • 19
  • 48
  • 1
    as mentioned in my comment below the question, this behaviour can be customized to achieve what OP is looking for – boop_the_snoot Aug 31 '22 at 18:28
  • @kelly, thanks for your response - but if I put the underscore in front of _components doesn't that prevent it from becoming a real route? – user12457151 Aug 31 '22 at 18:30
  • @user12457151 I don't think so, unless they've changed something in the newest version of Next.js... which I doubt, because some people *do* want routes to start with `_`, and besides, importing from `_components` is not as clean as importing from the top level components folder. With path aliases, importing from the top level is even cleaner. – kelsny Aug 31 '22 at 18:37