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

如何解决运行Vitest与TypeORM时的import语句模块外使用语法错误

Vitest测试报错 SyntaxError: Cannot use import statement outside a module 解决记录

问题背景

运行依赖数据库连接的Vitest测试时触发错误:SyntaxError: Cannot use import statement outside a module,该问题出在更新TypeORM迁移生成脚本之后。

相关配置

更新后的TypeORM迁移生成脚本:

"migration:generate": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ./src/infra/db/postgres/helpers/data-source.helper.ts migration:generate"

此脚本生成的迁移文件为TypeScript格式,例如1683049252085-CreateUsersTable.ts。

临时解决方法

将生成的迁移文件扩展名从.ts修改为.mjs,Vitest即可恢复正常运行。

补充优化思路

如果不想每次手动修改扩展名,可以调整TypeORM配置,指定生成.mjs格式的迁移文件;或者在Vitest配置中添加对迁移目录下.ts文件的转译处理,确保Vitest能正确识别其中的ES模块语法。

内容的提问来源于stack exchange,提问作者Carlos Oliveira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:42:37