使用parcel搭建three.js开发环境

发布时间 2023-07-05 22:04:28作者: Z朱子泉

为了方便模块化进行three.js项目的学习和开发,又不用学习太多的配置,增加学习成本,所以就使用Parcel这个web应用打包工具。

Parcel官网:https://v2.parceljs.cn/getting-started/webapp/

1、安装

​ 在开始之前,您需要安装 Node 和 npm,并为您的项目创建一个目录。然后,使用 npm 将 Parcel 安装到您的应用程序中:

npm install parcel-bundler --save-dev

image-20230705205443576

2、项目设置

​ 现在已经安装了 Parcel,让我们为我们的应用程序创建一些源文件。Parcel 接受任何类型的文件作为入口点,但 HTML 文件是一个很好的起点。Parcel 将从那里遵循您的所有依赖项来构建您的应用程序。

​ 创建src文件夹,并且创建index.html文件

<!DOCTYPE html>
<html lang="en">
  <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" />
    <title>Document</title>
    <link rel="stylesheet" href="./assets/css/style.css" />
  </head>
  <body>
    <script src="./main/main.js" type="module"></script>
  </body>
</html> 

image-20230705210409058

  • 设置1个css文件

    *{
       margin: 0; 
       padding: 0;
    }
    body{
      background-color: skyblue;  
    }
    

    image-20230705210549537

  • 创建一个main.js

import * as THREE from "three";

//console.log(THREE);

// 目标:了解three.js最基本的内容

// 1、创建场景
const scene = new THREE.Scene();

// 2、创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// 设置相机位置
camera.position.set(0, 0, 10);
scene.add(camera);

// 添加物体
// 创建几何体
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const cubeMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
// 根据几何体和材质创建物体
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
// 将几何体添加到场景中
scene.add(cube);

// 初始化渲染器
const renderer = new THREE.WebGLRenderer();
// 设置渲染的尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);
// console.log(renderer);
// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);

// 使用渲染器,通过相机将场景渲染进来
renderer.render(scene, camera);


3、打包脚本

到目前为止,我们一直在parcel直接运行 CLI,但在您的package.json文件中创建一些脚本以简化此操作会很有用。我们还将设置一个脚本来使用该命令构建您的应用程序以进行生产。parcel build最后,您还可以使用该字段在一个地方声明您的条目source,这样您就不需要在每个parcel命令中重复它们。

  • package.json:
{
  "name": "01-three_basic",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "parcel src/index.html",
    "build": "parcel build src/index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "parcel-bundler": "^1.12.5"
  }
}

image-20230705211551348

image-20230705213251437

image-20230705213924381