javascript - Gatsby 中库的条件导入
问题描述
我正在尝试这样做:
if (typeof window !== `undefined`) {
import Keyboard from "react-simple-keyboard"
import "react-simple-keyboard/build/css/index.css"
}
但我明白了
'import' and 'export' may only appear at the top level (12:2)
我能做些什么吗?仅当我们在浏览器中时,我才需要加载键盘。不是在构建期间。
解决方案
您应该使用React.lazy
组件,并且require()
.
该
React.lazy
函数允许您将动态导入呈现为常规组件。
if (typeof window !== `undefined`) {
import Keyboard from "react-simple-keyboard"
import "react-simple-keyboard/build/css/index.css"
}
// Becomes
if (typeof window !== `undefined`) {
// Component
const Keyboard = React.lazy(() => import('react-simple-keyboard'));
// Resolve
require('react-simple-keyboard/build/css/index.css');
}
推荐阅读
- java - 配置 SpringBootApplication 以从属性读取时遇到问题
- python - 双正则表达式搜索循环产生问题
- swift - Swift 中的保护声明
- python - 将 Simple Imputer 与 Pandas 数据框一起使用?
- angular - 指令正在更改父禁用属性
- pandas - Pandas - 创建最大键值对的 DataFrame
- vuejs2 - 如何在 ckeditor 5 vue 中使用代码示例?
- wordpress - 图片上传时缺少临时文件夹问题
- python - 条件循环橄榄球抽签的列表操作
- javascript - 保持填充 DOM 的顺序与对象顺序相同