【发布时间】:2021-08-11 16:56:16
【问题描述】:
场景
我正在处理一个小组项目,其中一位项目维护人员希望使用 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 问题吗?最终,我该如何解决这个问题?
尝试
-
import { GLTFLoader } from 'three-full'; // material.customProgramCacheKey is not a function -
import { GLTFLoader } from 'three'; TypeError: three__WEBPACK_IMPORTED_MODULE_3__.GLTFLoader is not a constructor -
new THREE.GLTFLoader(); TypeError: three__WEBPACK_IMPORTED_MODULE_3__.GLTFLoader is not a constructor -
import { GLTFLoader } from 'https://threejs.org/examples/jsm/loaders/GLTFLoader.js'; // Webpack supports "data:" and "file:" URIs by default. You may need an additional plugin to handle "https:" URIs. - package.json
{ "type": "module } - 等等等等
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);
【问题讨论】:
-
这是否有助于回答问题:NextJS + react-hook-mousetrap : “Cannot use import statement outside a module”?使用
next-transpile-modules的不同库但相同的解决方案。 -
@juliomalves 很好的发现。开箱即用这对我不起作用,但我敢打赌,转译是我最终必须要做的。当我有更多时间检查时,我会报告。谢谢!
标签: webpack import three.js next.js