Cypress Fixture无法从JavaScript导入TypeScript文件问题求助
Cypress Fixture中JS导入TS文件找不到模块的解决方法
问题情况
我有两个Cypress fixture文件:
cypress/fixtures/myFixture.js
import Something from "./somewhere"; ...
cypress/fixtures/somewhere.ts
export default function Something(): number { return 1; }
运行测试时触发错误:
Error: Can't walk dependency graph: Cannot find module './somewhere' from '/path/myFixture.js'
已经试过在Cypress目录添加tsconfig.json、使用ts-loader,但问题没解决——Cypress一直找somewhere.js而不是somewhere.ts,但Cypress v10文档明明说原生支持TypeScript。
解决方法
1. 导入时显式写.ts后缀
直接在JS文件的导入语句里加上.ts后缀,让模块解析器直接定位到目标文件:
import Something from "./somewhere.ts";
2. 配置Cypress的webpack解析规则
Cypress v10默认用webpack处理模块,修改cypress.config.js,自定义webpack配置,添加对.ts后缀的解析支持:
const { defineConfig } = require("cypress"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { const webpack = require('@cypress/webpack-preprocessor'); const options = { webpackOptions: { resolve: { extensions: ['.ts', '.js'] // 把.ts放在前面优先解析 }, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, use: 'ts-loader' } ] } } }; on('file:preprocessor', webpack(options)); }, }, });
同时保证Cypress根目录的tsconfig.json配置正确,参考示例:
{ "compilerOptions": { "target": "es5", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["**/*.ts", "**/*.js"] // 包含所有ts和js文件 }
3. 把JS fixture转成TS文件
既然Cypress原生支持TS,直接将myFixture.js重命名为myFixture.ts,这样导入时不用加后缀也能正常解析TS文件,还能获得类型检查的好处。
内容的提问来源于stack exchange,提问作者user17851340
相关产品推荐
相关产品推荐

