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

React+TypeScript项目Jest运行报错:无法在模块外使用import语句

解决React+TypeScript项目中Jest的ES模块导入错误

问题重现

运行Jest时遇到以下报错:

C:\projects\my-project\web\node_modules\swiper\react\swiper-react.js:13
    import { Swiper } from './swiper.js';
    SyntaxError: Cannot use import statement outside a module

或者:

C:\projects\my-project\web\node_modules\ssr-window\ssr-window.esm.js:148
    export { extend, getDocument, getWindow, ssrDocument, ssrWindow };
    ^^^^^^
    SyntaxError: Unexpected token 'export'

解决方案

1. 修正transformIgnorePatterns配置

当前配置仅包含swiper和lib,但ssr-window是swiper的依赖模块,同样需要被Jest转译。修改package.json中的jest配置:

"transformIgnorePatterns": [
  "/node_modules/(?!swiper|ssr-window|lib)/"
]

正则说明:排除node_modules下除swiper、ssr-window、lib之外的所有模块,让Jest对这几个模块进行ES转CommonJS处理。

2. 拆分transform规则,用babel-jest处理JS文件

ts-jest对纯ES模块的JS文件转译支持有限,将JS/JSX文件的转译交给babel-jest处理,修改package.json的jest配置:

"transform": {
  "^.+\\.(ts|tsx)$": "ts-jest",
  "^.+\\.(js|jsx)$": "babel-jest"
}

3. 优化Babel测试环境配置

更新.babelrc,确保测试环境下的编译目标匹配当前Node版本,同时强制转译ES模块:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ],
  "env": {
    "test": {
      "presets": [
        ["@babel/preset-env", { "targets": { "node": "current" } }],
        "@babel/preset-react",
        "@babel/preset-typescript"
      ],
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
  }
}

4. 为测试单独配置tsconfig

创建tsconfig.test.json文件,关闭isolatedModules以适配Jest的转译逻辑:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "isolatedModules": false
  }
}

然后在package.json的jest配置中指定该文件:

"jest": {
  "preset": "ts-jest",
  "tsConfig": "tsconfig.test.json",
  // ...保留其他已有配置
}

5. 清除Jest缓存并重新测试

执行命令清除旧缓存,避免配置变更不生效:

jest --clearCache

随后重新运行测试:

npm run test

内容的提问来源于stack exchange,提问作者Milad Zai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:24:54