Vite+React+TypeScript项目开发正常但构建失败求助
问题场景
基于Vite+React+TypeScript的项目,开发模式运行正常,但执行build时出现以下错误:
[commonjs--resolver] Unexpected token (9:4) in C:/···/node_modules/typedarray-pool/pool.js
file: C:/···/node_modules/gl-react/lib/createSurface.js:9:4
7: //Legacy pool support
8: if(!global.__TYPEDARRAY_POOL) {
9: global.__TYPEDARRAY_POOL = {
^
11: , UINT16 : dup([32, 0])
error during build:
SyntaxError: Unexpected token (9:4)
同时存在矛盾:vite.config.js中定义global: {}时dev正常但build报错;移除该定义后build成功但页面白屏。
解决方案
1. 修正global的定义
将global映射到浏览器环境的window对象,替代空对象定义,同时满足dev和build的需求:
// vite.config.js import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], base: './', define: { global: 'window', // 替换原有的global: {} }, })
2. 强制Vite转译相关依赖
typedarray-pool使用了旧的JavaScript语法(对象字面量开头的逗号),Vite默认不会转译node_modules中的依赖,导致构建时解析失败。需要配置Vite对gl-react和typedarray-pool进行转译:
// vite.config.js 完整配置 import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], base: './', define: { global: 'window', }, optimizeDeps: { include: ['gl-react', 'typedarray-pool'], esbuildOptions: { target: 'es2015' } }, build: { commonjsOptions: { include: [/typedarray-pool/, /gl-react/, /node_modules/] } } })
3. 可选:升级gl-react版本
检查gl-react的最新版本,若新版本已替换或修复了typedarray-pool的依赖问题,直接升级依赖包可能更彻底解决问题:
npm update gl-react gl-react-dom
原理说明
- 将
global映射到window:符合浏览器环境的全局对象规范,既解决了开发模式下的全局变量缺失问题,又避免了构建时解析器对空对象的语法误解。 - 转译依赖:通过
optimizeDeps和build.commonjsOptions配置,让Vite在预构建和打包阶段处理这两个依赖的旧语法,解决SyntaxError。
内容的提问来源于stack exchange,提问作者Daniel Zufrí Quesada

