three.js升级版本之后出现You may need an appropriate loader to handle this file type?

1、当使用three156版本时,在js中自定义某个类继承 THREE.BufferGeometry 会出现TypeError: Class constructor BufferGeometry cannot be invoked without 'new'
2、如果将three.js的版本改为167时,会出现 ERROR Failed to compile with 1 errors 18:54:20 error in ./node_modules/three/build/three.module.js Module parse failed: Unexpected token (34163:58) You may need an appropriate loader to handle this file type.
这个问题应该怎样解决?

期望提升three的版本之后不要报错且可正常运行

阅读 551
avatarAI BotBETA

问题原因分析:

  1. r156版本错误:Three.js 自 r125+ 开始全面转向 ES6 类语法,传统构造函数继承方式失效。
  2. r167版本错误:Three.js 的 ES Module 版本(.module.js)可能包含现代语法,未被 Webpack/Babel 正确处理。

解决方案:两步同步操作

步骤一:代码层修复(解决继承错误)

// 旧写法(原型继承)会报错 ❌
function CustomGeometry() {
  THREE.BufferGeometry.call(this);
}
CustomGeometry.prototype = Object.create(THREE.BufferGeometry.prototype);

// 新写法(ES6 类继承)✅
class CustomGeometry extends THREE.BufferGeometry {
  constructor() {
    super();
    // 你的初始化代码
  }
}

步骤二:构建工具配置(以 Webpack 为例)

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        // 关键排除项 ↓
        exclude: /node_modules\/(?!(three)\/).*/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
}

配套依赖升级:

npm install --save-dev webpack@5 babel-loader@9 @babel/core@7 @babel/preset-env@7

验证方案:

  1. 检查构建配置是否允许处理 three 模块
  2. 确认类继承语法已全面转为 ES6 形式
  3. 确保 three 版本在 package.json 中准确指定:

    "dependencies": {
      "three": "^0.167.0"
    }

备选方案: 若仍存在问题,可尝试直接引入 UMD 版本:

import * as THREE from 'three/build/three'; // 代替 three.module.js
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进