在 Gatsby 中有条件地导入库
Conditional Import of Library in 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()
.
The React.lazy
function lets you render a dynamic import as a regular component.
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 键盘 = 导入('react-simple-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])
我正在尝试这样做:
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()
.
The
React.lazy
function lets you render a dynamic import as a regular component.
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 键盘 = 导入('react-simple-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])