Javascript NextJS+;“反应钩捕鼠器”:;无法在模块外部使用导入语句";-钩子的动态导入?
我是初学者。正在尝试Next.js,但我正在努力解决以下问题。刚刚尝试安装了Javascript NextJS+;“反应钩捕鼠器”:;无法在模块外部使用导入语句";-钩子的动态导入?,javascript,reactjs,react-hooks,next.js,importerror,Javascript,Reactjs,React Hooks,Next.js,Importerror,我是初学者。正在尝试Next.js,但我正在努力解决以下问题。刚刚尝试安装了react hook mousetrap,并像往常一样导入了它: import useMousetrap from "react-hook-mousetrap"; 这给了我以下错误: SyntaxError: Cannot use import statement outside a module 1 > module.exports = require("react-hook-mo
react hook mousetrap
,并像往常一样导入了它:
import useMousetrap from "react-hook-mousetrap";
这给了我以下错误:
SyntaxError: Cannot use import statement outside a module
1 > module.exports = require("react-hook-mousetrap");
我不知道这是什么意思?然后我想这可能是nextjs的SSR的问题,因为我的库启用了热键,并且将使用一些浏览器API。如果你已经知道我在错误的轨道上,你现在可以停止阅读了
然而,我接下来做的是:我尝试了动态导入:
1。使用next/Dynamic动态导入
我遇到的第一件事是next/dynamic
,但这似乎只适用于JSX/React组件(如果我错了,请纠正我)。在这里,我将导入并使用React hook
2。使用等待(…)进行动态导入。默认值
所以我试过了,但我不知道该怎么做:
我需要在组件的顶层使用钩子,不能使组件异步,现在不知道该怎么做
const MyComponent = () => {
// (1) TRIED THIS:
const useMousetrap = await import("react-hook-mousetrap").default;
//can't use the hook here since my Component is not async; Can't make the Component async, since this breaks stuff
// (2) TRIED THIS:
(async () => {
const useMousetrap = (await import("react-hook-mousetrap")).default;
// in this async function i can't use the hook, because it needs to be called at the top level.
})()
//....
}
如果您有任何建议,我们将不胜感激 发生此错误是因为
react hook mousetrap
作为ESM库导出。您可以在Next.config.js
中使用Next.js传输它
constwithTM=require('next-transfile-modules')(['react-hook-mousetrap']);
module.exports=withTM({/*您的Next.js config*/});