Skip to content
Advertisement

“Cannot use import statement outside a module” error when importing react-hook-mousetrap in Next.js

Trying out Next.js but I’m struggling with the following. Just tried to install react-hook-mousetrap and imported it like I normally would:

JavaScript

This gives me the following error:

JavaScript

I am not sure what this means? I then thought it might be a problem with Nextjs’s SSR, since my library enables hotkeys and will use some browser APIs. If you already know that I am on the wrong track here you can stop reading now.

What I did next however was this, I tried dynamic imports:

1. Dynamic import with next/dynamic

First thing I came across was next/dynamic, but this seems to be for JSX / React Components only (correct me if I’m wrong). Here I will be importing and using a React hook.

2. Dynamic import with await (…).default

So I tried dynamically importing it as a module, but I’m not sure how to do this exactly.

I need to use my hook at the top level of my component, can’t make that Component async and now don’t know what to do?

JavaScript

Any advice here would be appreciated!

Advertisement

Answer

The error occurs because react-hook-mousetrap is exported as an ESM library. You can have Next.js transpile it using next-transpile-modules in your next.config.js.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement