如何在Nuxt 3项目中正确引入并使用TroisJS
Nuxt项目集成TroisJS/Three.js实现方案
方案一:正确引入TroisJS
- 首先安装依赖:执行
npm install troisjs - 在项目根目录的
plugins文件夹下,新建文件troisjs.client.ts(.client后缀是关键,标记该插件仅在客户端加载,避免SSR阶段因为缺少浏览器API报错),文件内容如下:
import { TroisJSVuePlugin } from 'troisjs' export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(TroisJSVuePlugin) })
- 不需要额外在
nuxt.config.ts中添加配置,Nuxt会自动扫描plugins目录完成插件注册。使用TroisJS组件时如果仍遇到SSR相关报错,可以用Nuxt内置的<ClientOnly>组件包裹3D场景部分。
方案二:直接使用原生Three.js
如果不需要TroisJS的封装能力,直接用原生Three.js配置更灵活,步骤如下:
- 安装依赖:执行
npm install three,使用TS的话可以额外安装类型包npm install -D @types/three - 不需要全局注册,直接在需要使用3D场景的组件中,在
onMounted生命周期内初始化Three.js实例即可(onMounted仅在客户端执行,天然规避SSR报错),最小实现示例:
<template> <div ref="containerRef" class="w-full h-[600px]"></div> </template> <script setup> import * as THREE from 'three' import { ref, onMounted } from 'vue' const containerRef = ref(null) onMounted(() => { // 初始化基础实例 const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, containerRef.value.clientWidth / containerRef.value.clientHeight, 0.1, 1000) const renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setSize(containerRef.value.clientWidth, containerRef.value.clientHeight) containerRef.value.appendChild(renderer.domElement) // 添加测试物体 const cube = new THREE.Mesh( new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({ color: 0x2563eb }) ) scene.add(cube) camera.position.z = 3 // 渲染循环 const animate = () => { requestAnimationFrame(animate) cube.rotation.x += 0.01 cube.rotation.y += 0.01 renderer.render(scene, camera) } animate() }) </script>
注意:所有依赖浏览器WebGL、DOM API的3D相关逻辑,都不要在setup顶层直接执行,必须放在客户端执行的钩子/插件中,否则会导致服务端构建失败。
内容的提问来源于stack exchange,提问作者composersucks
相关产品推荐
相关产品推荐

