Home > front end >  Gatsby - Trying to Generate and Download a Text File
Gatsby - Trying to Generate and Download a Text File

Time:02-21

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;

CodePudding user response:

From what I've managed to find out is that I'm not even supposed to use Blob with Node at all

That's partially true. You're right when you say that Blob is not using Node at all, however, when you run gatsby build, your code is parsed and bundled in a Node server, that's why it breaks the code. In other words, your code is interpreted by the Node server, where there's no window or other global objects (such as document) because they are not even defined yet. On the other hand, when you run gatsby develop your code is interpreted by the browser, where there's the window and other global objects exist.

You can easily bypass this by adding the following condition:

if(typeof window !== "undefined")

This will check if you are on the server or in the client.

Try using:

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

export default Download;
  • Related