Home > other >  Module not found: Can't resolve 'fs' - Calling function
Module not found: Can't resolve 'fs' - Calling function

Time:05-28

I have a NextJS project in which one component is using getStaticProps and getStaticPaths to get a list of files:

The getAllBlogPosts function is in another file (see below)

import { GetStaticPaths, GetStaticProps } from "next";
import { useRouter } from "next/router";
import BlogSummaryPage from "../index";
import { getAllBlogPosts } from "../_functions";
import { BLOGPOSTS_PER_PAGE } from "../../../config/blogposts";

const BlogPage = ({ blogposts }: any) => {
  const router = useRouter();
  const { num = 1 } = router.query;
  return <BlogSummaryPage blogposts={blogposts} page={Number(num)} />;
};

const getStaticPaths: GetStaticPaths = async () => {
  const blogposts = getAllBlogPosts();
  let pageCount = Math.ceil(blogposts.length / BLOGPOSTS_PER_PAGE);
  const paths = [];
  while (pageCount) {
    paths.push({ params: { num: `${pageCount}` } });
    pageCount -= 1;
  }

  return {
    paths,
    fallback: false,
  };
};

const getStaticProps: GetStaticProps = async () => {
  const blogposts = getAllBlogPosts();
  return {
    props: {
      blogposts,
    },
  };
};

export { getStaticProps, getStaticPaths };

export default BlogPage;

In another file:

import fs from "fs";
import matter from "gray-matter";
import { IBlogpost } from "./_types";

const getAllBlogPosts = (): Array<IBlogpost> => {
  const blogpostFilenames = fs.readdirSync("blogposts");
  const blogposts = blogpostFilenames
    .reverse()
    .filter((filename) => filename !== `template.md`)
    .map((fileName) => {
      const readBlogFile = fs.readFileSync(`blogposts/${fileName}`, "utf-8");
      const {
        data: { date, image, imgAlt, imgHeight, imgWidth, slug, summary, title },
        content,
      } = matter(readBlogFile);
      return {
        content,
        date,
        image,
        imgAlt,
        imgHeight,
        imgWidth,
        slug,
        summary,
        title,
      };
    });

  return blogposts;
};

export { getAllBlogPosts };

When doing a yarn build I'm getting the following error message:

yarn run v1.22.18
$ next build
info  - Checking validity of types  
info  - Creating an optimized production build  
Failed to compile.

./pages/blog/_functions.ts
Module not found: Can't resolve 'fs' in '/home/george/code/myblog/pages/blog'

I'm only calling the getAllBlogPosts function from these two functions. Using yarn dev everything works as expected. I want to keep it in a separate file, because in the future other pages will use it.

Any tips on how to fix this? Ty!

CodePudding user response:

Having a module with shared functions inside the 'pages' directory seems like a bad idea. NextJS will assume that every file in 'pages' should be compiled as if it was a page.

I just created a tiny server with a shared function to read a text file using fs, and called that from getStaticProps/getStaticPaths/getServerSideProps with no issues. I was having trouble getting the error at all. Then I simply copied the shared module (which I'd put above the pages directory) into 'pages' and got exactly your error.

  • Related