2

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.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
userjmillohara
  • 457
  • 5
  • 25

3 Answers3

1

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');
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Thanks a lot. This does let me build it. But I get an `illegal constructor` error when I run it any idea why this might be? would I do this type of import where I do the other imports (that's where I put it so far)? – userjmillohara Jul 21 '20 at 12:12
  • I don't know and its not related to your question, you should ask a new question with your current problem. – Dennis Vash Jul 21 '20 at 12:13
  • It is related. I am asking you where in my code I need to put the code that you suggested. Next to the other imports? In a function? Right now it's crashing, unfortunately. – userjmillohara Jul 21 '20 at 12:16
  • You put it instead of your current your code, that's how you make dynamic imports. I can't tell your exactly in which file, I can't know your project structure. – Dennis Vash Jul 21 '20 at 12:18
  • That's fine. I don't need to know which file. Thanks a lot for your answer. – userjmillohara Jul 21 '20 at 12:19
0

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

lotype
  • 593
  • 3
  • 8
0

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])
ED209
  • 2,422
  • 1
  • 14
  • 13