How do you import a javascript package from a cdn/script tag in React?

JavascriptHtmlnode.jsReactjsEcmascript 6

Javascript Problem Overview


I'd like to import this javascript package in React

<script src="https://cdn.dwolla.com/1/dwolla.js"></script>

However, there is no NPM package, so I can't import it as such:

import dwolla from 'dwolla'

or

import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'

so whenver I try

dwolla.configure(...)

I get an error saying that dwolla is undefined. How do I solve this?

Thanks

Javascript Solutions


Solution 1 - Javascript

Go to the index.html file and import the script

<script src="https://cdn.dwolla.com/1/dwolla.js"></script>

Then, in the file where dwolla is being imported, set it to a variable

const dwolla = window.dwolla;

Solution 2 - Javascript

This question is getting older, but I found a nice way to approach this using the react-helmet library which I feel is more idiomatic to the way React works. I used it today to solve a problem similar to your Dwolla question:

import React from "react";
import Helmet from "react-helmet";

export class ExampleComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            myExternalLib: null
        };
        
        this.handleScriptInject = this.handleScriptInject.bind(this);
    }
    
    handleScriptInject({ scriptTags }) {
        if (scriptTags) {
            const scriptTag = scriptTags[0];
            scriptTag.onload = () => {
                // I don't really like referencing window.
                console.log(`myExternalLib loaded!`, window.myExternalLib);
                this.setState({
                    myExternalLib: window.myExternalLib
                });
            };
        }
    }

    render() {
        return (<div>
            {/* Load the myExternalLib.js library. */}
            <Helmet
                script={[{ src: "https://someexternaldomain.com/myExternalLib.js" }]}
                // Helmet doesn't support `onload` in script objects so we have to hack in our own
                onChangeClientState={(newState, addedTags) => this.handleScriptInject(addedTags)}
            />
            <div>
                {this.state.myExternalLib !== null
                    ? "We can display any UI/whatever depending on myExternalLib without worrying about null references and race conditions."
                    : "myExternalLib is loading..."}
            </div>
        </div>);
    }
}

The use of this.state means that React will automatically be watching the value of myExternalLib and update the DOM appropriately.

Credit: https://github.com/nfl/react-helmet/issues/146#issuecomment-271552211

Solution 3 - Javascript

You can't require or import modules from a URL.

https://stackoverflow.com/questions/34607252/es6-import-module-from-url

What you can do is make an HTTP request to get the script content & execute it, as in the answer for https://stackoverflow.com/questions/7809397/how-to-require-from-url-in-node-js

But this would be a bad solution since your code compilation would depend on an external HTTP call.

A good solution would be to download the file into your codebase and import it from there. You could commit the file to git if the file doesn't change much & are allowed to do it. Otherwise, a build step could download the file.

Solution 4 - Javascript

for typescript developers

const newWindowObject = window as any; // cast it with any type

let pushNotification = newWindowObject.OneSignal; // now OneSignal object will be accessible in typescript without error

Solution 5 - Javascript

Add the script tag in your index.html and if you are using Webpack, you can use this webpack plugin https://webpack.js.org/plugins/provide-plugin/

Solution 6 - Javascript

var _loaded = {};
function addScript(url) {
  if (!loaded[url]) {
    var s = document.createElement('script');
    s.src = url;
    document.head.appendChild(s);
    _loaded[url] = true;
  }
}

how to load javascript file from cdn server in a component

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy HerzogView Question on Stackoverflow
Solution 1 - JavascriptJeremy HerzogView Answer on Stackoverflow
Solution 2 - JavascriptAaron NewtonView Answer on Stackoverflow
Solution 3 - JavascriptvsrView Answer on Stackoverflow
Solution 4 - JavascriptAshish MukarneView Answer on Stackoverflow
Solution 5 - JavascriptAswin KView Answer on Stackoverflow
Solution 6 - Javascripthassan khademiView Answer on Stackoverflow