拒绝配置地狱!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.jsonscripts里面添加运行入口:

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开发干货

相关推荐
tao3556671 天前
【用AI学前端】准备工作
前端·人工智能
利刃大大1 天前
【Vue】自定义指令directives && 指令钩子 && IntersectionObserver
前端·javascript·vue.js
共享家95271 天前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Halo_tjn1 天前
基于封装的专项 知识点
java·前端·python·算法
m0_748229991 天前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
C澒1 天前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..1 天前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
hhy_smile1 天前
Class in Python
java·前端·python
小邓吖1 天前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
南风知我意9571 天前
【前端面试2】基础面试(杂项)
前端·面试·职场和发展