【问题标题】:SyntaxError: Cannot use import statement outside a module while using `fast-image-zoom`语法错误:使用“fast-image-zoom”时无法在模块外使用导入语句
【发布时间】: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


【解决方案1】:

将您的文件更改为以下

_app.js 代码

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;

【讨论】:

  • 谢谢你的作品。我第一次单击缩放时是否有任何原因,它相当慢?只有在我的应用程序上,Stackblitz 才能正常工作:)
  • 不知道这一点,因为我自己没有尝试过图书馆。但是您可以检查 chrome 开发工具并进行分析,这可以为您提供有关改进该部分的见解。
  • 从来没有做过分析,所以如果你有任何推荐的资源可以让我知道:)
猜你喜欢
  • 2021-01-05
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2022-11-17
  • 2021-12-03
  • 2021-07-08
相关资源
最近更新 更多