You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript项目Vite构建报错:import.meta相关语法错误

React + TypeScript + Vite项目构建时出现import.meta语法错误

我正在开发一个用Vite打包的React + TypeScript项目,所有依赖都已正确安装,开发服务器运行完全正常,但执行构建命令时遇到了和import.meta相关的语法错误,报错信息如下:

X [ERROR] Expected identifier but found "import"

  (define name):1:0:
    1 │ import.meta.dirname
      ╵ ~~~~~~

X [ERROR] Expected identifier but found "import"

  (define name):1:0:
    1 │ import.meta.filename
      ╵ ~~~~~~

failed to load config from path/to/vite.config.ts
error during build:
Error: Build failed with 3 errors:
...

解决方案

  • 替换Node.js ESM特性为Vite兼容写法:import.meta.dirname和import.meta.filename是Node.js专属的ESM API,Vite在构建阶段处理配置文件时,可能不会将其当作Node环境代码解析。你可以用Node.js内置的fileURLToPath和path模块来实现相同效果:
import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

注意需要确保你的项目已经安装了@types/node(用于TypeScript类型支持)。

  • 确认配置文件的模块格式:如果你的package.json中设置了"type": "module",那么配置文件可以用ESM语法;如果没有这个配置,建议改用CommonJS格式,直接使用__dirname(需要在tsconfig中启用node相关的类型库)。

  • 排查第三方插件问题:如果不是你自己的代码里用到了这些API,检查一下项目中安装的Vite插件,有些插件可能会在构建过程中错误注入Node环境的API,导致语法报错。

内容的提问来源于stack exchange,提问作者er.arunkushwaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 10:07:33