盖茨比图书馆的有条件导入



我正在尝试这样做:

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');
}
  • 查看导入与需要
  • 此外,您应该检查import()

您可以使用动态导入语法

const Keyboard=导入("实际键盘"(

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports

Gatsby支持开箱即用的动态导入。

useEffect(() => {
async function dynamicImportModule() {
const dynamicModule = (await import('some-module'))
// perform remaining tasks with dynamicModule
}
dynamicImportModule()
}, [someDependency])

最新更新