jnordberg / gif.js

JavaScript GIF encoding library
http://jnordberg.github.io/gif.js/
MIT License
4.74k stars 668 forks source link

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

Open RiverTwilight opened 4 years ago

RiverTwilight commented 4 years ago

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.

1j01 commented 4 years ago

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
    });
kosich commented 4 years ago

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/