0

I use standard nextron (Next + electron.js) to jump start my project (https://github.com/saltyshiomix/nextron)

In one particular case, I need to read a file template.html to variable (String). so I think I'll use fs.readFileSync()

When I use import fs from "fs", the compiler complains that fs is not available. (refer to this Module not found: Can't resolve 'fs' in Next.js application)

The accepted answer on that thread, recommends me to update the next.config.js file into:

/// I need this to load image from static files
const withImages = require('next-images')

module.exports = withImages({
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on `fs` module
    if (!isServer) {
      config.node = {
        fs: 'empty'
      }
    }

    return config
  }
})

But the solution doesn't work for me.

import fs from 'fs'

const generatePDF = () => {
    let content = fs.readFileSync("./template.html")
}  

What's wrong here?

enter image description here enter image description here

DennyHiu
  • 4,861
  • 8
  • 48
  • 80

1 Answers1

1

I think the problem is that you are trying to use fs module (which is node.js native module) on the client side. The webpack change you've added tells webpack to ignore fs module for the client (or replace it with the stub), but you are still trying to use it.

One way to workaround this is to render your component on the server side only. Please read this documentation - https://nextjs.org/docs/advanced-features/react-18/server-components

Honestly, generally it is bad idea to try to read files/templates on the client side.

But if you really need to get that html on the client, I recommend to create an API which will read html on the server and return as a string. Then you can insert it into the DOM as unsafe html. This will not require massing around with native node modules.

Hope this helps.