SyntaxError:当使用' fast-image-zoom '时,不能在模块外使用import语句



我正在尝试在我的React/Next.js应用程序中使用快速图像缩放&我得到以下错误:

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.nextserverpages_app.js:20969:18)
at __webpack_require__ (my-app.nextserverwebpack-runtime.js:25:42)
my-appnode_modulesfast-image-zoomsrcindex.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中的2行注释以查看错误。

我怎么解决它?

将文件更改为

<<p>_app.js代码/strong>
import { useEffect } from 'react';
function MyApp({ Component, pageProps }) {
useEffect(() => {
const loadImageZoom = async () => {
const imageZoom = await import('fast-image-zoom').then(
mod => mod.default
);
imageZoom();
};
loadImageZoom();
}, []);
return <Component {...pageProps} />;
}
export default MyApp;

最新更新