我们之前说webgl的时候,是以夯实基础为目的。
而现在的three,我会逐步往实战靠拢。
现在,webpack 依旧是主流的模块打包工具,这在大部分公司的项目开发中是必不可少的。
ts和three 是绝配,three本身就是用ts写的,ts可以为three 项目提前做好规则约束,使项目的开发更加顺畅。
因此,我接下来会跟大说一下如何用webpack+ts 写three。
对于主流的前端框架vue、react,前期还不是特别需要,我会放到后面说。
我当前选择的webpack 是最新版本的webpack 5,具体指南可参考官网。
1.创建一个目录,初始化 npm
mkdir 01-start
cd 01-start
npm init -y
2.调整 package.json 文件,以便确保我们安装包是 private(私有的),并且移除 main 入口。这可以防止意外发布你的代码。
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
- "main": "index.js",
+ "private": true,
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"webpack": "^5.38.1",
"webpack-cli": "^4.7.2",
}
}
3.安装依赖文件
- webpack 相关的依赖
npm install webpack webpack-cli webpack-dev-server --save-dev
- ts 相关的依赖
npm install typescript ts-loader --save-dev
- three 相关的依赖
npm install three @types/three --save
package.json 如下:
{
"name": "three-lesson-02",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "webpack serve --open",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^9.2.8",
"typescript": "^4.6.2",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"dependencies": {
"@types/three": "^0.138.0",
"three": "^0.138.3"
}
}
4.建立项目文件。
- 目录结构
01-start
|- dist
|- 01-helloWorld.html
|- src
|- helloWorld.ts
|- package.json
|- package-lock.json
|- tsconfig.json
|- webpack.config.js
- dist/01-helloWorld.html
helloWorld
- src/helloWorld.ts
const str:string='Hello World'
console.log(str)
- webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: {
helloWorld: './src/helloWorld.ts',
},
devtool: 'inline-source-map',
devServer: {
static: './dist',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /.tsx?$/, loader: "ts-loader" }
]
}
};