在Next.js中导入REACT-HOOK-Mousetrap时出现“Cannot Use IMPORT STATEMENT OUT A MODULE”错误

bttbmeg0  于 2022-10-21  发布在  React
关注(0)|答案(2)|浏览(381)

正在尝试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-mousetrap");

我不确定这是什么意思?然后我想这可能是Nextjs的SSR的问题,因为我的库启用了热键,并将使用一些浏览器API。如果你已经知道我在错误的轨道上,你现在可以停止阅读了。
然而,我接下来做的是,我尝试了动态导入:

1.下一步动态导入/动态导入

我遇到的第一件事是next/dynamic,但这似乎只适用于JSX/Reaction组件(如果我错了,请纠正我)。在这里,我将导入并使用Reaction挂钩

2.等待动态导入(...).默认

所以我试了试dynamically importing it as a module,但我不确定具体怎么做。
我需要在我的组件的顶层使用我的钩子,无法使该组件异步,现在不知道该怎么办?

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.

    })()

 //....
}

如有任何建议,我们将不胜感激!

yrefmtwq

yrefmtwq1#

出现错误的原因是react-hook-mousetrap作为ESM库导出。您可以让Next.js在您的next.config.js中使用next-transpile-modules来转换它。

const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);

module.exports = withTM({ /* Your Next.js config */});
brccelvz

brccelvz2#

我不知道我的答案是否真实,但我今天面对的是这个问题,以及我做了什么:

//test component for modal 
const Button: React.FC<{close?: () => void}> = ({ close }) => (
 <React.Fragment>
    <button type="button" onClick={ close }>Close</button>
 </React.Fragment>
);

// async call import react custom hook in next js whithout a dynamic 
//import
let newHook;

(async () => {
 const { hookFromNodeModules } = 
 await import('path/to/hook');

 newHook = hookFromNodeModules;
})();

export default function Home() {
// check if hook is available
const openModal = newHook && newHook();

const { t } = useTranslation('common');

// useCallback for update call function when hook is available
const handleOpen = React.useCallback(() => {
    openModal?.openModal(Button, {});
}, [openModal]);

 return ( ...your code )
}

希望这能有所帮助!)
screen from next.js app

相关问题