我正在尝试这样做:
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)
对此我能做些什么?只有在浏览器中时,才需要加载键盘。不是在构建期间。
答案 0 :(得分:0)
您应使用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');
}
import()
。答案 1 :(得分:0)
您可以使用动态导入语法
const Keyboard = import('react-simple-keyboard')
参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports
答案 2 :(得分:0)
Gatsby 支持开箱即用的动态导入。
useEffect(() => {
async function dynamicImportModule() {
const dynamicModule = (await import('some-module'))
// perform remaining tasks with dynamicModule
}
dynamicImportModule()
}, [someDependency])