Reputation: 467
I am trying to do this:
if (typeof window !== `undefined`) {
import Keyboard from "react-simple-keyboard"
import "react-simple-keyboard/build/css/index.css"
}
But I get
'import' and 'export' may only appear at the top level (12:2)
Anything I can do about this? I need to load my keyboard only if we're in the browser. Not during build.
Upvotes: 2
Views: 1858
Reputation: 2442
Gatsby supports dynamic imports out of the box.
useEffect(() => {
async function dynamicImportModule() {
const dynamicModule = (await import('some-module'))
// perform remaining tasks with dynamicModule
}
dynamicImportModule()
}, [someDependency])
Upvotes: 0
Reputation: 613
You may use the dynamic import syntax
const Keyboard = import('react-simple-keyboard')
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports
Upvotes: 0
Reputation: 53964
You should use React.lazy
for the component, and 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()
.Upvotes: 1