Jerlam
Jerlam

Reputation: 1101

Add an external script to React and create new instance

I am trying to implement this github project to my React web app. It is an external script to put a fancy canvas in the background.

I have tried to load it:

import {WarpSpeed} from './warpspeed.js'
import WarpSpeed from './warpspeed.js'

And then create a new instance:

let x = new WarpSpeed("canvasID")

But it throws an error:

TypeError: __WEBPACK_IMPORTED_MODULE_4__helpers_warpspeed___default.a is not a constructor

I also tried to use react-load-script, but it does not make sense I cannot call new WarpSpeed after, because it is undefined.

Upvotes: 0

Views: 411

Answers (2)

azrahel
azrahel

Reputation: 1213

According to this:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only

other info I've found and after checking source code of WarpSpeed.js, what you want seems impossible.

You can also confirm it here:

ES6 import equivalent of require() without exports

You should probably add proper export to WarpSpeed.js file. Maybe fork the project, modify it so it is ES5+ compatibile and create pull request. Probably lib creator will be greateful ;)

Upvotes: 1

Tameem Safi
Tameem Safi

Reputation: 728

The module you are trying to use will not work with commonjs importing. You will need to wrap the whole thing inside of a universal module definition.

Please use the one here:

https://gist.githubusercontent.com/tameemsafi/0d909a4060640b948f37ec59460f20d4/raw/c7f4e9020ccb1fb0a9dcf54221c67249030640eb/warpspeed-umd.js

I have wrapped it in a UMD IFFE which will allow you to use ES6 import. I also changed the window.requestAnimationFrame polyfill to a better version.

You can place the code inside of a file warpspeed.js.

CommonJS:

const WarpSpeed = require('./warpspeed.js');

ES6 (Requires transpiling to commonjs):

import WarpSpeed from './warpspeed.js'

Upvotes: 1

Related Questions