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

Vue项目Cypress e2e测试引入@faker-js/faker报Webpack编译错误

问题结论

该报错确实由依赖版本兼容问题导致。
你当前使用的Cypress 8.3.0版本内置Webpack 4构建能力,默认未配置针对.mjs后缀ESM模块的解析loader,而高版本@faker-js/faker默认输出ESM格式的.mjs产物,构建时无法识别对应语法就会抛出该编译错误。


问题相关上下文

测试代码

import { faker } from '@faker-js/faker';

const username = faker.internet.userName();
const password = faker.internet.password();
it('form elements should be correct', () => {
  cy.get(userLoginElement.username).type(username).should('have.value', username);
  cy.get(userLoginElement.password).type(password).should('have.value', password);
  cy.get(userLoginElement.loginButton).should('exist');
});

cypress.json配置

{
  "pluginsFile": "tests/e2e/plugins/index.js",
  "baseUrl": "http://127.0.0.1:8080"
}

Cypress插件配置

module.exports = (on, config) => {
  return Object.assign({}, config, {
    fixturesFolder: 'tests/e2e/fixtures',
    integrationFolder: 'tests/e2e/specs',
    screenshotsFolder: 'tests/e2e/screenshots',
    videosFolder: 'tests/e2e/videos',
    supportFile: 'tests/e2e/support/index.js'
  })
}

相关依赖版本

"faker": "^6.6.6",
"@vue/cli-plugin-e2e-cypress": "~5.0.0",
"@vue/cli-plugin-unit-jest": "~5.0.0",
"cypress": "^8.3.0",

报错信息

执行vue-cli-service test:e2e时抛出:

Error: Webpack Compilation Error
./node_modules/@faker-js/faker/dist/esm/chunk-4J2PVEV7.mjs 1:1430
Module parse failed: Unexpected token (1:1430)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

可行解决方案

任选以下一种方案即可修复问题:

  • 降级@faker-js/faker至兼容CommonJS规范的最后稳定版本,无需修改现有测试代码,执行安装命令npm install @faker-js/faker@7.6.0 -D后重新运行测试即可。注意不要和已停止维护的旧版faker包混淆,当前社区维护的正式包为@faker-js/faker。
  • 升级Cypress至10.0及以上版本,新版Cypress内置的构建工具原生支持ESM格式的.mjs模块解析,注意大版本升级存在配置、目录结构的破坏性变更,需要同步调整现有e2e测试配置适配新版规范。
  • 保留现有依赖版本,扩展Cypress的Webpack预处理器配置,增加.mjs文件解析规则,修改插件配置文件如下:
// tests/e2e/plugins/index.js
const webpackPreprocessor = require('@cypress/webpack-preprocessor')

module.exports = (on, config) => {
  const webpackOptions = {
    module: {
      rules: [
        {
          test: /\.mjs$/,
          include: /node_modules/,
          type: 'javascript/auto'
        }
      ]
    },
    resolve: {
      extensions: ['.mjs', '.js', '.json']
    }
  }
  on('file:preprocessor', webpackPreprocessor({ webpackOptions }))

  return Object.assign({}, config, {
    fixturesFolder: 'tests/e2e/fixtures',
    integrationFolder: 'tests/e2e/specs',
    screenshotsFolder: 'tests/e2e/screenshots',
    videosFolder: 'tests/e2e/videos',
    supportFile: 'tests/e2e/support/index.js'
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:48:20