通过Typescript使用ThreeJS ES6原生模块可以按照以下步骤进行:
npm install three typescript ts-loader webpack webpack-cli --save-dev
- src/
- index.ts
- tsconfig.json
- webpack.config.js
tsconfig.json
文件,并添加以下内容:{
"compilerOptions": {
"target": "es6",
"module": "es6",
"moduleResolution": "node",
"esModuleInterop": true,
"sourceMap": true,
"outDir": "dist"
}
}
webpack.config.js
文件,并添加以下内容:const path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
};
src/index.ts
文件中编写ThreeJS代码,例如: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();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
npx webpack
然后,打开生成的dist/index.html
文件即可看到ThreeJS场景的效果。
值得注意的是,以上步骤假设你已经安装了Webpack和TypeScript的相关工具。如果没有安装,可以使用以下命令进行安装:
npm install webpack webpack-cli typescript ts-loader --global
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云对象存储(COS)。
领取专属 10元无门槛券
手把手带您无忧上云