You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Parcel打包时,Three.js通过import.meta.url导入.glb文件报错

解决Parcel打包Three.js项目中GLB模型加载问题

问题1:import.meta.url语法错误

你遇到的Cannot use 'import.meta' outside a module错误,核心是Parcel 1(你安装的parcel-bundler对应Parcel 1版本)对import.meta的支持需要额外适配,且需确保脚本的模块环境配置正确。

解决方案:

用Parcel推荐的静态资源导入方式处理模型文件,Parcel会自动解析路径并完成打包,无需依赖import.meta.url:

import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
// 直接导入模型文件,Parcel自动处理路径
import terrainModel from './terrain.glb';

new GLTFLoader().load(terrainModel, gltf => { 
  let model = gltf.scene;
  model.position.y += 0.48;
  scene.add(model);
});

问题2:直接用相对路径加载模型被识别为HTML

直接写loader.load('terrain.glb')时模型不显示、报错缺少<标签,是因为Parcel开发服务器会将未正确解析的资源请求 fallback 到HTML入口文件,导致GLTFLoader拿到的是index.html内容而非模型文件。

解决方案:

  1. 修正相对路径:确保路径相对于当前JS文件的位置。比如scripts.js在src/js/目录,模型在src/根目录,路径应写为../terrain.glb;若模型和JS同目录,直接用./terrain.glb。
  2. 优先用静态导入(即问题1的方案),让Parcel完全接管资源路径处理,从根源避免路径错误。

额外优化建议

  • 建议升级到Parcel 2(当前主流版本),它对ES模块和静态资源的支持更完善:
    # 卸载旧版本
    npm uninstall parcel-bundler --save-dev
    # 安装Parcel 2
    npm install parcel --save-dev
    # 启动命令不变
    npx parcel ./src/index.html
    
  • 不要移除HTML中<script>标签的type="module"属性,你使用了ES模块的import语法,Parcel需要该标识来正确处理模块。

内容的提问来源于stack exchange,提问作者Anton Nagler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 05:59:53