[英]Import external JS library and use it inside React component
I have some code in React like this:我在 React 中有一些这样的代码:
useEffect(() => {
TICautocapture(etc..);
That TICautocapture()
function is already defined in an external js file, let's say: TICautocapture()
function 已经在外部 js 文件中定义,假设:
http:://some-cdn.example.com/library.js
So how could I use that library
methods on my React component?那么如何在我的 React 组件上使用该library
方法呢?
I need it to be declared inside the Component, otherwise it wont find the name of the function.我需要在组件内声明它,否则它不会找到 function 的名称。
by the way, I cant download the file locally because the library is being updated constantly, so I need to import from an external url.顺便说一句,我无法在本地下载文件,因为库正在不断更新,所以我需要从外部 url 导入。
EDIT:编辑:
The code of the library is like this:库的代码是这样的:
// 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));
}
And from there I need to use the TICautocapture()
method.从那里我需要使用TICautocapture()
方法。
Your file is loading var TICautocapture
into the global scope and also setting a property autocapture
on window.jQuery.fn
.您的文件正在将var TICautocapture
加载到全局 scope 并在window.jQuery.fn
上设置属性autocapture
捕获。
I am not confident that this is correct, but I would try using Webpack externals by putting the following in your webpack.config.js
我不确定这是正确的,但我会尝试使用Webpack 外部组件,方法是将以下内容放入您的webpack.config.js
module.exports = {
// ...
externalsType: 'script',
externals: {
autocapture: [
'http://some-cdn.example.com/library.js',
'autocapture', // or maybe 'TICautocapture'?
'TICautocapture',
],
},
};
And then try importing it in your component file:然后尝试将其导入您的组件文件中:
import {TICautocapture} from "autocapture";
If it's just a file you have in the project, you can simply import it to where you need like so:如果它只是您在项目中的一个文件,您可以简单地将其导入到您需要的位置,如下所示:
// if it's the default export
import TICautocapture from "./file.js";
or或者
// if it's NOT the default export and other
// functions and variables could be imported from that file
import { TICautocapture } from "./file.js";
Of course, in the cases I mentioned, you should make sure they're exported in the files they're exported using export
or export default
.当然,在我提到的情况下,您应该确保将它们导出到使用export
或export default
导出的文件中。
If the file is being delivered by a CDN, I'm not really sure but I think just by adding it the the root HTML file will make it available everywhere for you.如果文件是由 CDN 交付的,我不太确定,但我认为只需将其添加到根 HTML 文件即可使其随处可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.