![](/img/trans.png)
[英]can i use normal javascript code if in that code imported some module
[英]javascript - Check if an imported module exists in the project and if not use some sort of fallback
我有一個 react native 模塊,我想在其中使用一個通用模塊來做一件小事,但我不想強迫某人為此包含它。
所以我想檢查模塊是否存在,如果是這樣的話,使用它,如果不做一個解決方法。 代碼可能如下所示:
import Module from 'react-native-non-existing-module'
if (Module) {
// do something with the Module
} else {
// use fallback
}
但我得到一個錯誤:
錯誤:未定義無法從
src/myFile.tsx
解析模塊react-native-non-existing-module
:在項目中找不到 react-native-non-existing-module。如果您確定該模塊存在,請嘗試以下步驟:
- 清除守望者手表:watchman watch-del-all
- 刪除 node_modules:rm -rf node_modules 並運行 yarn install
- 重置 Metro 的緩存:yarn start --reset-cache
- 刪除緩存:rm -rf /tmp/metro-*
我也試過這個:
如果模塊存在以及是否存在要加載,如何檢查節點?
但這對我也不起作用
I don't see why you would import a package you didn't install, if you're in doubt of a particular package, you can easily check your package.json file in the root directory
如果您的意思是條件導入,那么您將使用 es6 做的是
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.