使用Axios、Cypress和TypeScript写API测试遇模块语法错误求解决
解决
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' 错误 1. 修复package.json的语法与配置错误
你的package.json存在语法问题,且sourceType: module不是Node.js识别ES模块的正确配置,调整如下:
{ "main": "index.ts", "type": "module", "cypress-cucumber-preprocessor": { "nonGlobalStepDefinitions": true }, "dependencies": { "@types/browserify": "^12.0.37", "@types/cypress-cucumber-preprocessor": "^4.0.1", "axios": "^1.2.0", "cypress": "^9.7.0", "cypress-cucumber-preprocessor": "^4.3.1", "install": "^0.13.0", "tsc": "^2.0.4" }, "devDependencies": { "@babel/core": "^7.20.2", "@babel/preset-env": "^7.20.2", "@cucumber/cucumber": "^8.8.0", "@cypress/webpack-preprocessor": "^5.15.5", "typescript": "^4.9.3", "webpack": "^5.75.0" } }
- 将无效的
sourceType: module替换为type: module,这是Node.js启用ES模块的标准配置 - 移除多余逗号,修复JSON语法错误
2. 统一模块规范
选项A:使用ES模块(推荐配合TypeScript)
将测试文件扩展名改为.ts,并替换require为ES模块语法:
import axios from 'axios'; axios.get('http://localhost:8080/') .then(response => { console.log(response); }) .catch(error => { console.log(error); }) .finally(() => { // 最终执行逻辑 });
同时更新tsconfig.json,添加模块配置确保编译兼容:
{ "compilerOptions": { "target": "es5", "module": "ESNext", "lib": ["es5", "dom"], "types": ["cypress", "node"], "resolveJsonModule": true, "esModuleInterop": true }, "include": ["**/*.ts"], "exclude": ["node_modules"] }
module: ESNext指定TypeScript编译为ES模块esModuleInterop解决CommonJS模块的导入兼容问题
选项B:继续使用CommonJS
若不想切换ES模块,移除package.json中的type: module,并修改tsconfig.json的模块设置:
{ "compilerOptions": { "target": "es5", "module": "CommonJS", "lib": ["es5", "dom"], "types": ["cypress", "node"], "resolveJsonModule": true }, "include": ["**/*.ts"], "exclude": ["node_modules"] }
测试文件可保留.js或改为.ts,继续使用require语法即可。
3. 配置Webpack预处理器
由于使用了cypress-cucumber-preprocessor,需确保Webpack正确处理TypeScript文件,创建或修改webpack.config.js:
module.exports = { resolve: { extensions: ['.ts', '.js'], }, module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, };
4. 重置依赖环境
执行以下命令清理并重新安装依赖:
rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者qa_automation
相关产品推荐
相关产品推荐

