Uncaught TypeError: _particles2.default.load is no

2020-07-27 05:13发布

问题:

Am having trouble importing the particles.js library.

Am using create-react-app, and am following the instructions on the particles js github page also.

After initiating 'create-react-app', I install particles.js

npm install particles.js --save

then in the App.js file the relevant parts I have are:

import particlesJS from 'particles.js'

componentDidMount(){
    //particles.js github page says to load package like so:
    particlesJS.load('particles-js', 'assets/particles.json', function() {
      console.log('callback - particles.js config loaded');
    });
},

render() {
    return (
       <div>
            //div to include particles canvas, as specified in particles.js github page         
            <div id="particles-js"></div>
       </div>
);

}

However the console gives the error Uncaught TypeError: _particles2.default.load is not a function

And if I put to console.log(particlesJS) it gives an empty object, so I am pretty sure the problem is with how I am loading the package. Basically, the package is not even being loaded, that is why there is no .load() function available on the particlesJS object.

Any ideas how to fix this?

By the way, have got the package working through the 'react-particles-js' package, however still curious to see how to get it to work by using the package.js package directly.

回答1:

It looks like the library was written without regard for JavaScript bundlers, so it's not really working with the import statement like you would expect. Instead it sets a global variable on the window object.

So to use it you could do something like:

import 'particles.js/particles';
const particlesJS = window.particlesJS;

Hope this helps!