[英]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.