正在尝试 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
我遇到的第一件事是next/dynamic,但这似乎仅适用于 JSX/React 组件(如果我错了,请纠正我)。在这里,我将导入和使用React hook。
2. 使用 await (...).default 动态导入
所以我尝试将它作为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.
})()
//....
}
任何建议在这里将不胜感激!