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

如何修改import语句实现本地调用已下载的three.module.js文件?

如何将three.js远程导入改为本地文件调用

第一步:确认本地文件结构

把你下载的three.module.js和你的HTML文件放在同一目录下(或者按习惯放在子文件夹,比如libs/目录)。

第二步:修改导入路径

将原来的远程CDN路径替换为本地文件的相对路径:

  • 如果文件和HTML同目录,修改为:
    import * as THREE from './three.module.js';
    
  • 如果放在子文件夹(比如libs/),修改为:
    import * as THREE from './libs/three.module.js';
    

第三步:必须用本地服务器打开HTML文件

注意:不能直接双击HTML文件在浏览器打开,因为浏览器对本地文件的模块导入有跨域限制,会报错。你可以用以下任意一种方式启动本地服务器:

  • 用VSCode的「Live Server」插件,右键HTML文件选择「Open with Live Server」
  • 用Python启动简易服务器:
    • Python 3:在终端执行 python -m http.server 8000
    • Python 2:在终端执行 python -m SimpleHTTPServer 8000
      然后在浏览器访问 http://localhost:8000 打开你的HTML文件

修改后的完整代码示例

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
        </style>
    </head>
    <body>
        <script type="module">
            // 这里改成本地相对路径
            import * as THREE from './three.module.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 geometry = new THREE.BoxGeometry( 1, 1, 1 );
            const material = new THREE.MeshBasicMaterial( { color: 0x0000FF } );
            const cube = new THREE.Mesh( geometry, material );
            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();
        </script>
    </body>
</html>

常见问题排查

  • 如果还是报错,先检查路径是否正确:确认three.module.js的位置和你写的相对路径匹配
  • 检查浏览器控制台的错误信息:如果是CORS相关错误,说明你没通过本地服务器打开文件
  • 确认下载的three.module.js文件完整,没有损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:42:18