首页 > 解决方案 > 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)

我能做些什么吗?仅当我们在浏览器中时,我才需要加载键盘。不是在构建期间。

标签: javascriptnode.jsreactjsimporterror

解决方案


您应该使用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');
}

推荐阅读