jnordberg / gif.js

JavaScript GIF encoding library

Home Page:http://jnordberg.github.io/gif.js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The location of gif.worker.js cannot be located correctly when building with createreactapp

RiverTwilight opened this issue · comments

The console will display ‘Uncaught SyntaxError: Unexpected token '<'’.And when I open the gif.worker.js file on the console, the index.html file is displayed.

You need to use the workerScript option to point to a path where the gif.worker.js is served.

Create React App loves to serve index.html, it does it any time it doesn't find a file, instead of a 404.
Try putting the gif.worker.js somewhere in the public folder, and find where you can load the file from the server, then update workerScript to match that path.

Or you could try loading the worker from a Blob, pasting in the gif.worker.js into a string:

    var workerStr =  `...`; // worker code as a string.
    var workerBlob = new Blob([workerStr], {
        type: 'application/javascript'
    });
    var gif = new GIF({
        workers: 2,
        workerScript: URL.createObjectURL(workerBlob),
        quality: 10
    });

CRA requires public files to be accessed via the %PUBLIC_URL% environment variable.
Which means that in scripts you need to define the workerScript like

var gif = new GIF({
  // ...
  workerScript: process.env.PUBLIC_URL + '/gif.worker.js'
});

You can find more details on official CRA docs:
https://create-react-app.dev/docs/using-the-public-folder/