DEV Community

Amandeep Minhas
Amandeep Minhas

Posted on

How pageExtensions helped me migrate from CRA to NextJS

I had the following file structure for pages in my Create React App Project.

/components
  /Navbar
    index.js
    Navbar.js
    Navbar.scss

/pages
  /Home
    /components
      /HeroSection
        index.js
        HeroSection.js
        HeroSection.scss
    index.js
    Home.js
    Home.scss

  /About
    /components
      /HeroSection
        index.js
        HeroSection.js
        HeroSection.scss
    index.js
    About.js
    About.scss
Enter fullscreen mode Exit fullscreen mode

We use a components directory inside pages directory to nest all page related components inside the pages/<page-name>/component directory as they are only going to be used in that particular page and not intended to be reused by other pages. This is more for modularity than reusability.
For reusable components, we use the top level components/ directory. For components such as Navbar, Footer, Button, etc.

While migrating to NextJS, this pattern will be an issue because NextJS by default will create a route based on the directory structure you have inside the pages directory.
So by default, NextJS will build a page for route localhost:3000/Home/components/HeroSection which isn't really what we intend to do here.

Solution :-
Use pageExtensions in your next.config.js

// next.config.js
module.exports = {
  pageExtensions: ['page.js']
};
Enter fullscreen mode Exit fullscreen mode

What we are doing here is letting NextJS know that all our pages will be suffixed with page.js. So our pages will now be index.page.js

Now directory structure in NextJS will update to :-

/components
  /Navbar
    index.js
    Navbar.js
    Navbar.module.scss

/pages
  /home
    /components
      /HeroSection
        index.js
        HeroSection.js
        HeroSection.module.scss
    index.page.js <-- UPDATED
    Home.js
    Home.scss

  /about
    /components
      /HeroSection
        index.js
        HeroSection.js
        HeroSection.module.scss
    index.page.js <-- UPDATED
    About.js
    About.module.scss

  _app.page.js
  _document.page.js
Enter fullscreen mode Exit fullscreen mode

Keep in mind that when you do this, you will also need to update your _document.js and _app.js to _document.page.js and _app.page.js, respectively.

Another thing I had to update is use css modules for component level styling. More on that in another post.

Top comments (0)