一、新建一个文件夹做为项目目录,文件夹名不包含中文及特殊字符,例如:three-study。
在文件夹内按顺序执行以下命令
-
初始化项目
npm init -y -
安装vite工具
npm i vite -D -
安装three.js
npm i three
项目目录如下:
二、创建文件
- 在根目录创建
index.html文件,index.html 是vite 打包工具的入口文件; - 根目录创建
src目录; - 在src 目录里创建一个ts文件:
main.ts(vite 默认支持typescript);
注:2、3步,创建目录名、文件名随意
此时项目目录如下:
三、关联文件
-
在index.html 文件中引入 main.ts
<script type="module" src="./src/main.ts"></script>; -
在body 中增加div标签,
<div id="app"></div>index.html如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>study-three</title> </head> <body> <div id="app"></div> <script type="module" src="./src/main.ts"></script> </body> </html>
四、测试
- 在main.ts 中增加一行代码
console.log('*******hello three****'); - 打开终端 输入命令 npx vite
运行结果如下
五、配置命令
在 package.json 文件中的scripts下配置如下命令
- 开发时dev-server命令:
"dev": "vite --open", - 代码编译命令:
"build": "vite build", - 运行编译后代码的命令:
"preview": "vite preview --open"
后面就不用输入npx 命令了,在终端输入npm run dev,即可
六、引入three
- 安装three.js 的typescript类型文件包
npm i @types/three -D - 在main.ts 中引入three 并输入three 的版本
import * as THREE from 'three';
console.log(THREE.REVISION);
运行结果如下:说明正常
[vite] connecting...
[vite] connected.
155