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

如何配置Cypress使其正确识别app/tsconfig中定义的路径别名~/*

核心问题说明

TypeScript 中配置的 paths 路径别名仅作用于静态类型校验阶段,Cypress 运行时的模块解析由其内部使用的打包工具(默认是 Webpack,也可配置为 Vite)完成,打包工具默认不会读取 TS 配置的别名,因此会出现模块找不到的报错。

解决方案

场景1:使用 Cypress 默认 Webpack 预处理器

  1. 先安装必要依赖(如果项目未安装):
npm install --save-dev @cypress/webpack-preprocessor ts-loader
  1. 修改 cypress.config.ts 配置,给 Webpack 添加别名映射:
// cypress.config.ts
import { defineConfig } from 'cypress'
import path from 'path'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      const webpackPreprocessor = require('@cypress/webpack-preprocessor')
      on('file:preprocessor', webpackPreprocessor({
        webpackOptions: {
          resolve: {
            alias: {
              // 匹配你tsconfig里的~别名,映射到app目录
              '~': path.resolve(__dirname, 'app')
            },
            extensions: ['.ts', '.js', '.json']
          },
          module: {
            rules: [
              {
                test: /\.ts$/,
                exclude: /node_modules/,
                use: 'ts-loader'
              }
            ]
          }
        }
      }))
      return config
    }
  }
})

场景2:项目使用 Vite 构建

可以直接复用 Vite 的别名配置,无需重复编写:

  1. 安装依赖:
npm install --save-dev cypress-vite
  1. 修改 cypress.config.ts 配置:
// cypress.config.ts
import { defineConfig } from 'cypress'
import vitePreprocessor from 'cypress-vite'
import path from 'path'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 直接传入你项目的vite配置路径即可自动读取别名
      on('file:preprocessor', vitePreprocessor(path.resolve(__dirname, 'vite.config.ts')))
      return config
    }
  }
})

额外优化:修正 Cypress 侧 TS 配置

修改 cypress/tsconfig.json 的 include 字段,将 app 目录的文件加入类型校验范围,避免类型报错:

{
  "extends": "../app/tsconfig.json",
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress", "node", "@testing-library/cypress"],
  },
  "include": ["../node_modules/cypress", "**/*.ts", "../app/**/*.ts"]
}

配置完成后重启 Cypress 服务即可正常识别路径别名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:54:07