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

HTML中使用import引入three.js模块报错,求解决方案

解决方案

1. 修正脚本类型

浏览器默认将<script>标签视为普通脚本,不支持ES模块的import语法。你需要给引入threeCode.js的脚本标签添加type="module"属性:

<!-- index.html -->
<script type="module" src="./threeCode.js"></script>

2. 正确指向three.js模块路径

由于你通过npm安装了three.js,它的ES模块入口文件位于node_modules/three/build/three.module.js,需要在threeCode.js中修改导入路径:

// threeCode.js
import * as THREE from './node_modules/three/build/three.module.js';

// 示例three.js逻辑代码
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const cube = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial({ color: 0x00ff00 }));
scene.add(cube);
camera.position.z = 5;

function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
animate();

替代方案:使用CDN快速引入(适合原型开发)

如果不想依赖本地node_modules,可以直接通过CDN导入three.js模块,省去npm安装步骤:

// threeCode.js
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@latest/build/three.module.js';

// 后续逻辑同上

关键说明

  • 加上type="module"后,浏览器会按ES模块规则解析脚本,支持import/export语法。
  • 本地npm安装的three.js必须指向three.module.js,这是官方提供的ES模块版本,不能直接写./three。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:30:43