![](/img/trans.png)
[英]How can I solve this error in React App? ('Component' is not defined no-undef)
[英]Variable is not defined, no-undef; How can I bypass this error?
我有一個 react-create-app 項目,它在我的公共 index.html 中鏈接了一個專有庫,它讓我可以使用一個名為“SingularPlayer”的變量。
<script src="https://www.something.com/libs/singularplayer.js"></script>
例如,我應該能夠:
const previewObj = SingularPlayer(iframeId);
但我不能,因為我不斷收到此錯誤:
第 67 行:'SingularPlayer' 未定義 no-undef
我試過把這些放在我的 package.json 中,但這些也不起作用:
"rules": {
"no-undef": 0
},
"globals": {
"SingularPlayer": false
},
"env": {
"SingularPlayer": true
}
編輯:我的項目不會讓我運行(npm start),直到我修復錯誤
您可以使用以下檢查繞過錯誤,
(typeof fn === "function") - 只有當它是函數時才返回真
const previewObj = ((typeof SingularPlayer === "function") && SingularPlayer(iframeId));
為避免編譯錯誤,建議下載腳本並從本地引用
如果未定義“SingularPlayer”,則它不會包含在 JS 中。
您需要在要從中訪問它的 JS 文件中導入 singleplayer.js 文件。
import SingularPlayer from '{url}/singularplayer.js'
你不能從 ES6 中的 URL 導入模塊,如果你必須包含來自另一個主機的 JS,請按照以下問題的答案: https : //stackoverflow.com/a/44877953/4953804
我有一個類似的問題 - 即使通過window.ConstantName
也無法訪問全局常量。
由於這條評論指導我創建了一個新的代理文件,我解決了這個問題。 第一行的注釋是解決錯誤的魔法。
// eslint-disable-next-line no-undef
const ConstantNameProxy = ConstantName;
export default ConstantNameProxy;
然后當我需要使用常量時,我導入並使用代理,例如:
import ConstantNameProxy from './path/to/proxy/file';
console.log(ConstantNameProxy);
您當然可以在使用全局常量的每一行之前添加注釋,或者例如在文件級別更全局地禁用錯誤,但這將是真實代碼周圍不必要的垃圾量,並可能隱藏其他真實錯誤.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.