我想在 React 中导入这个 javascript 包
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
但是,没有NPM包,所以我无法这样导入它:
import dwolla from 'dwolla'
或
import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'
所以每当我尝试
dwolla.configure(...)
我收到一条错误消息,指出 dwolla 未定义。我该如何解决这个问题?
转到index.html文件并导入脚本
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
然后,在导入 dwolla 的文件中,将其设置为变量
const dwolla = window.dwolla;
这个问题越来越老了,但我找到了一个很好的方法来使用
react-helmet
库来解决这个问题,我觉得这对于 React 的工作方式来说更惯用。我今天用它来解决类似于你的 Dwolla 问题的问题:
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>);
}
}
使用
this.state
意味着 React 将自动监视 myExternalLib 的值并相应地更新 DOM。
信用:https://github.com/nfl/react-helmet/issues/146#issuecomment-271552211
对于打字稿开发者
const newWindowObject = window as any;
// 使用任何类型进行转换
let pushNotification = newWindowObject.OneSignal;
// 现在 OneSignal 对象将可以在打字稿中访问而不会出现错误
您不能从 URL 请求或导入模块。
您可以做的是发出 HTTP 请求来获取脚本内容并执行它,如 how to require from URL in Node.js
的答案所示但这将是一个糟糕的解决方案,因为您的代码编译将依赖于外部 HTTP 调用。
一个好的解决方案是将文件下载到您的代码库中并从那里导入。 如果文件没有太大变化并且允许这样做,您可以将文件提交到 git。否则,构建步骤可能会下载该文件。
var _loaded = {};
function addScript(url) {
if (!loaded[url]) {
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);
_loaded[url] = true;
}
}
在你的index.html中添加script标签,如果你使用的是Webpack,你可以使用这个webpack插件https://webpack.js.org/plugins/provide-plugin/
//通过npm导入时
import dwolla from 'dwolla';
// 您现在可以直接在此模块中使用
dwolla
console.log(dwolla);