【发布时间】:2021-10-18 09:52:42
【问题描述】:
我尝试在我的 React/Next.js 应用程序中使用 fast-image-zoom,但出现以下错误:
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:353:18)
at wrapSafe (node:internal/modules/cjs/loader:1039:15)
at Module._compile (node:internal/modules/cjs/loader:1073:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at Object.fast-image-zoom (my-app\.next\server\pages\_app.js:20969:18)
at __webpack_require__ (my-app\.next\server\webpack-runtime.js:25:42)
my-app\node_modules\fast-image-zoom\src\index.js:1
import styles from './styles'
^^^^^^
我尝试按_app.tsx 中的原样调用它:
import imageZoom from 'fast-image-zoom';
imageZoom();
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
但它抛出了上述错误,因为它是一个纯 ESM 模块。
然后我尝试在_document.tsx 中使用它,例如:
async componentDidMount() {
dynamic(() => import('fast-image-zoom').then((mod) => mod.imageZoom), { ssr: false })
}
然后我没有错误,但它不起作用。
我在这里进行了复制-> https://stackblitz.com/edit/nextjs-edw9pk?file=pages%2F_app.js
您可以取消注释pages/_app.js 中的两行以查看错误。
我该如何解决?
【问题讨论】:
-
当您在
MyApp中调用imageZoom()时,错误会消失吗? -
@SinanYaman nope 因为该模块是纯 ESM,所以我需要检查它是否只能在客户端工作。我尝试使用
process.browser,但这也没有任何好处。
标签: javascript reactjs next.js server-side-rendering