Next.js seemingly erroneous message "SyntaxError: Cannot use import statement outside a module"

Next.js seemingly erroneous message "SyntaxError: Cannot use import statement outside a module"

场景

我正在处理一个小组项目,其中一位项目维护者想使用 Next.js,这是可以理解的。我们在项目中使用了 three.js,在利用 GLTFLoader 的同时,我已经 运行 进入了一些意料之外的东西。

SyntaxError: Cannot use import statement outside a module

这似乎是由于像这样导入 GLTFLoader 造成的

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

我有点理解为什么会发生这种情况,但请检查一下:如果我注释掉 import 行并刷新浏览器,那么我会看到一个没有预期错误的页面。现在页面正在热重载,如果我取消 GLTFLoader 导入和 GLTFLoader 代码的注释,那么一切都会按预期工作!

但是

如果我手动刷新页面,我会收到初始 SyntaxError 消息和描述,并且必须相应地注释掉和取消注释代码。

问题

为什么会这样?这是 Next.js 问题而不是 Webpack 问题吗?最后,我该如何解决这个问题?

尝试次数

next.config.js 这似乎很合适,因为这里可能需要添加一些东西

module.exports = {
  future: {
    webpack5: true,
  },
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.module.rules.push(
      // ...

      // Shaders
      {
        test: /\.(glsl|vs|fs|vert|frag)$/,
        exclude: /node_modules/,
        use: ['raw-loader'],
      }
    );
    return config;
  },
};

** 编辑 **

我想我找到了解决方法 https://onion2k.hashnode.dev/loading-a-gltf-model-in-react-three-fiber

** 临时解决方案 **

import { useGLTF } from '@react-three/drei'

const assetURL = "/asset/scene.gltf";
const Asset = useGLTF(assetURL);

scene.add(Asset.scene)

useGLTF.preload(assetURL);

我最终使用了 next/dynamic

import dynamic from 'next/dynamic';

...

const DynamicPackage = dynamic(() => import('package'), { ssr: false });