拒绝配置地狱!5 分钟搭建 Three.js + Parcel 完美开发环境

1. 序言

Parcel 不需要复杂的配置文件,你只需要指明一个 index.html,可以有效节省你在开发环境上配置时间。

2. 初始化

首先,我们需要一个干净的目录。打开终端,输入以下命令:

Bash 复制代码
mkdir three-parcel-demo
cd three-parcel-demo
npm init -y
npm install --save-dev parcel-bundler
npm install three

然后在package.json的scripts里面添加运行入口:

json 复制代码
 "scripts": {
    "dev": "npx parcel src/index.html",
    "build": "npx parcel build src/index.html"
  },

3. 项目结构搭建

Parcel 的强大在于它支持 HTML 入口。

  • index.html: 骨架
  • src/main.js: 灵魂
  • src/style.css: 皮肤

4. 编写核心代码

在 index.html 中引入脚本和样式表:

HTML 复制代码
<!DOCTYPE html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./assets/css/style.css"/>
</head>
<body>
    <canvas id="three-canvas"></canvas>
    <script src="./main/main.js" type="module"></script>
</body>
</html>

在 src/main.js 中快速启动:

JavaScript 复制代码
import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#three-canvas') });

renderer.setSize(window.innerWidth, window.innerHeight);

// 添加一个极简的几何体
const geometry = new THREE.IcosahedronGeometry(1, 0);
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

camera.position.z = 3;

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

5. 启动与魔法

现在,一个最简单的3D 开发环境已经搭建完成了,只需要在命令行输入:

Bash 复制代码
npm run dev

如此,你就可以在 http://localhost:1234 查看效果。

📂 核心代码与完整示例: my-three-app

总结

如果你喜欢本教程,记得点赞+收藏!关注我获取更多Three.js开发干货

相关推荐
Flynt9 小时前
AI 写的 Three.js 大屏,为什么越跑越卡?我在 Node 里复现了它的内存曲线
前端·ai编程·three.js
一个游离的指针11 小时前
Vue2:vue-router
前端·javascript·vue.js
火山引擎和TA的超级拍档们14 小时前
产品情报局 11 | AI 数据湖 LAS:打造大模型时代多模态数据底座
前端·后端
JavaGuide14 小时前
Gemini 真的变强了,写代码做视频的能力接近 Claude Opus5.5 了!
前端·ai编程
niceyayale14 小时前
WebRTC 延迟怎么调试:从 ICE 到 jitter buffer 的六个观测点
前端
aleimu14 小时前
Windows 11 右键打开 Cmder 2.0:从找不到菜单到默认使用 Cmder
前端·人工智能·后端
tryCbest14 小时前
Vue系列——第 20 篇:Vue Router 4——路由管理完全指南(上)
前端·javascript·vue.js
feixing_fx14 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
一条破秋裤14 小时前
【1115】【多线程】【笔记】
前端·chrome·笔记
黑十14 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能