[英]Import external JS library and use it inside React component
我在 React 中有一些这样的代码:
useEffect(() => {
TICautocapture(etc..);
TICautocapture()
function 已经在外部 js 文件中定义,假设:
http:://some-cdn.example.com/library.js
那么如何在我的 React 组件上使用该library
方法呢?
我需要在组件内声明它,否则它不会找到 function 的名称。
顺便说一句,我无法在本地下载文件,因为库正在不断更新,所以我需要从外部 url 导入。
编辑:
库的代码是这样的:
// http:://some-cdn.example.com/library.js
var TICautocapture = (function(){
var lib = {...}
var error_handler;
var handleError = (error_code, error_callback) => {...}
function autocapture(container, options){...}
return autocapture;
})();
if(window.jQuery){
(function($){
$.fn.autocapture = function(options){
TICautocapture(this.attr('id'), options);
}
}(jQuery));
}
从那里我需要使用TICautocapture()
方法。
您的文件正在将var TICautocapture
加载到全局 scope 并在window.jQuery.fn
上设置属性autocapture
捕获。
我不确定这是正确的,但我会尝试使用Webpack 外部组件,方法是将以下内容放入您的webpack.config.js
module.exports = {
// ...
externalsType: 'script',
externals: {
autocapture: [
'http://some-cdn.example.com/library.js',
'autocapture', // or maybe 'TICautocapture'?
'TICautocapture',
],
},
};
然后尝试将其导入您的组件文件中:
import {TICautocapture} from "autocapture";
如果它只是您在项目中的一个文件,您可以简单地将其导入到您需要的位置,如下所示:
// if it's the default export
import TICautocapture from "./file.js";
或者
// if it's NOT the default export and other
// functions and variables could be imported from that file
import { TICautocapture } from "./file.js";
当然,在我提到的情况下,您应该确保将它们导出到使用export
或export default
导出的文件中。
如果文件是由 CDN 交付的,我不太确定,但我认为只需将其添加到根 HTML 文件即可使其随处可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.