'Gatsby - Trying to Generate and Download a Text File

I've managed to create a function that generates a text file that the user can download.

It works perfectly when I run the development build of Gatsby, but when I build for production I get the error: WebpackError: ReferenceError: Blob is not defined

If I then try to add import {Blob} from "buffer" I get instead: WebpackError: ReferenceError: window is not defined and then it doesn't work with Gatsby develop anymore either.

From what I've managed to find out is that I'm not even supposed to use Blob with Node at all, and instead use Buffer, but I'm completely lost with that because it doesn't seem to replace Blob directly. Also, why does it work on my development build but not in production? Feels like I should be close to a solution?

Here is my function:


export function Download() {
  const data = new Blob(["Hello world"], {
    type: "text/plain;charset=utf-8",
  });
  const downloadLink = window.URL.createObjectURL(data);
  return downloadLink;
}

export default Download;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source