How to import javascript package from cdn / script tag in React?

I want to import this javascript package into React

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

However, the NPM package is missing, so I cannot import it as such:

 import dwolla from 'dwolla' 

or

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

so when i try

 dwolla.configure(...) 

I get a message that dwolla is undefined. How to solve this?

thanks

+7
source share
4 answers

Go to index.html file and import the script

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

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

 const dwolla = window.dwolla; 
+14
source

You cannot require or import modules from a URL.

ES6: import module from URL

What you can do is make an HTTP request to get the contents of the script and execute it, as in the answer, how to require the URL in Node.js

But that would be a bad decision, as your compilation of code would depend on an external HTTP call.

A good solution would be to upload the file to your code base and import it from there. You can transfer the git file if the file does not change much and is allowed to do so. Otherwise, the build step may load the file.

+1
source

Add a script tag to your index.html and if you use Webpack you can use this webpack plugin https://webpack.js.org/plugins/provide-plugin/

0
source

This question is getting old, but I found a good way to approach it using the helmet library which, in my opinion, is more idiomatic for React to work. I used this today to solve a problem similar to your Dwolls question:

 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>); } } 

Using this.state means that React will automatically monitor the value of myExternalLib and update the DOM accordingly.

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

0
source

Source: https://habr.com/ru/post/1269423/


All Articles