解决require is not defined报错:gltf-pipeline命令行/网页使用方法问询
gltf-pipeline调用解决方案
一、Node.js命令行调用(更简单,适合本地批量处理)
你之前运行node compress.js报错的核心原因是没有在当前工作目录安装对应npm依赖,Node无法识别你手动放入的gltf-pipeline源码文件夹为已安装模块,按以下步骤操作即可:
- 进入你的
basefolder目录,打开终端执行初始化命令:npm init -y - 安装所需依赖:
npm install gltf-pipeline fs-extra - 你原来写的
compress.js代码无需修改,直接运行即可正常执行压缩:node compress.js
额外提示:你已经可以正常使用gltf-pipeline的命令行工具的话,完全不用自己写脚本,一行命令就可以实现和你代码完全相同的效果:gltf-pipeline -i model.gltf -o modeldraco.gltf --draco.compressionLevel 10 --separateTextures
二、网页端调用
你之前网页端报错的核心原因是:gltf-pipeline默认是为Node.js环境编写的,使用CommonJS规范,浏览器原生不支持require语法和module变量,直接引入源码会报错。需要借助构建工具转换为浏览器可识别的格式,操作步骤如下:
- 还是在
basefolder目录下,执行命令安装构建工具和依赖:npm install vite gltf-pipeline - 修改
compress.js代码,把Node端的文件读写逻辑替换为浏览器端的文件处理逻辑:
import { processGltf } from 'gltf-pipeline'; // 绑定文件选择事件 document.getElementById('gltfInput').addEventListener('change', async (e) => { const file = e.target.files[0]; if (!file) return; // 读取用户上传的gltf文件 const reader = new FileReader(); reader.onload = async (ev) => { const gltf = JSON.parse(ev.target.result); const options = { dracoOptions: { compressionLevel: 10, }, separateTextures: true, }; // 执行压缩 const results = await processGltf(gltf, options); // 下载压缩后的gltf主文件 const gltfBlob = new Blob([JSON.stringify(results.gltf)], { type: 'application/json' }); const gltfUrl = URL.createObjectURL(gltfBlob); const downloadLink = document.createElement('a'); downloadLink.href = gltfUrl; downloadLink.download = 'modeldraco.gltf'; downloadLink.click(); // 下载分离出的纹理等资源文件 for (const relativePath in results.separateResources) { if (results.separateResources.hasOwnProperty(relativePath)) { const resource = results.separateResources[relativePath]; const resBlob = new Blob([resource]); const resUrl = URL.createObjectURL(resBlob); const resLink = document.createElement('a'); resLink.href = resUrl; resLink.download = relativePath; resLink.click(); } } }; reader.readAsText(file); });
- 修改
index.html内容,引入脚本时指定type="module":
<!DOCTYPE html> <html lang="zh-CN"> <body> <input type="file" id="gltfInput" accept=".gltf"> <script type="module" src="./compress.js"></script> </body> </html>
- 执行命令启动本地开发服务器:
npx vite
打开终端提示的本地地址,即可在网页端上传gltf文件完成压缩。
内容的提问来源于stack exchange,提问作者Bigboss01
相关产品推荐
相关产品推荐

