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

自定义Babel配置与Next.js SWC默认配置冲突及SWC插件配置咨询

在Next.js(SWC)中配置Cypress代码覆盖率解决方案

核心思路

Next.js默认使用SWC作为编译工具,存在.babelrc会强制切换到Babel导致构建失败。我们需要仅在测试环境启用SWC版的istanbul覆盖率插件,同时保留SWC作为生产构建工具,配合Cypress的代码覆盖率插件完成数据收集。

步骤1:安装SWC版istanbul插件

替换原有的babel-plugin-istanbul,安装SWC官方的覆盖率插件:

npm install --save-dev @swc/plugin-istanbul

步骤2:配置Next.js的SWC插件(next.config.ts)

仅在测试环境加载覆盖率插件,避免影响生产构建:

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    swcPlugins: process.env.NODE_ENV === 'test' ? [
      ['@swc/plugin-istanbul', {
        include: ['app/**/*', 'components/**/*'], // 按需调整项目源码路径
        exclude: ['node_modules/**/*', '.next/**/*'],
        extension: ['.ts', '.tsx', '.js', '.jsx']
      }]
    ] : []
  }
}

export default nextConfig

步骤3:调整Cypress配置(cypress.config.ts)

集成@cypress/code-coverage插件,确保能正确处理SWC生成的覆盖率数据:

// cypress.config.ts
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      require('@cypress/code-coverage/task')(on, config)
      // 兼容SWC的覆盖率数据处理
      on('file:preprocessor', require('@cypress/code-coverage/use-babelrc'))
      return config
    },
  },
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
    setupNodeEvents(on, config) {
      require('@cypress/code-coverage/task')(on, config)
      return config
    },
  },
})

步骤4:添加Cypress支持文件

在Cypress的支持文件中导入覆盖率支持:

// cypress/support/e2e.ts(组件测试对应component.ts)
import '@cypress/code-coverage/support'

步骤5:配置覆盖率报告(.nycrc)

调整nyc的配置,指定源码范围和报告格式:

{
  "extends": "@istanbuljs/nyc-config-typescript",
  "include": ["app/**/*", "components/**/*"],
  "exclude": ["node_modules", ".next", "cypress"],
  "reporter": ["lcov", "text", "html"]
}

步骤6:修改测试脚本(package.json)

确保测试时设置NODE_ENV=test,触发SWC加载覆盖率插件:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test:e2e": "NODE_ENV=test cypress run",
    "test:component": "NODE_ENV=test cypress run --component"
  }
}

注意事项

  • 确保@swc/plugin-istanbul的版本与Next.js依赖的@next/swc-*包版本兼容,避免编译报错。
  • 移除项目根目录的.babelrc文件,彻底恢复SWC的默认编译流程。

内容的提问来源于stack exchange,提问作者Ala Eddine Menai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:52:33