Jest报错:SyntaxError: Unexpected token 'export' 配置后仍未解决求助
Let's break down why this is happening and how to fix it:
Your current config enables Jest's experimental ESM support and skips all transformations (transform: {}), but the core issue is that Jest ignores transformations for node_modules by default—and the object-array-utils package is published as an ES Module (using export syntax) without a CommonJS fallback. Since you've disabled all transforms, Jest can't parse that ESM syntax when it encounters the package.
Here are the step-by-step fixes:
1. Configure Jest to Transpile the Problematic Package
We'll update your Jest config to run Babel on object-array-utils while still ignoring other node_modules packages.
Modify the jest section in your package.json:
"jest": { "testEnvironment": "jest-environment-node", "transform": { "^.+\\.js$": "babel-jest" }, "transformIgnorePatterns": [ "/node_modules/(?!object-array-utils)/" ] }
The transformIgnorePatterns regex tells Jest: "ignore everything in node_modules except the object-array-utils folder."
2. Install Required Babel Dependencies
You'll need Babel to convert the ES Module syntax to a format Jest can understand:
npm install --save-dev @babel/core @babel/preset-env babel-jest
3. Add a Babel Configuration File
Create a .babelrc file in your project root with these settings:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "current" } }] ] }
This configures Babel to transpile code to match your current Node.js version's supported syntax.
4. Keep Your Existing Test Script
Retain your test script in package.json—it enables the experimental ESM support needed for your own code:
"scripts": { "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" }
Why This Works
By targeting object-array-utils for transformation, we convert its ES Module syntax to CommonJS (which Jest can parse) while keeping your own ESM code functional with the experimental VM modules flag.
Alternative Check: If object-array-utils offers a CommonJS build (look for a main field pointing to a .cjs file in its package.json), you could try forcing Jest to resolve that version instead—but transpiling is the more reliable fix if no CommonJS build exists.
内容的提问来源于stack exchange,提问作者user2923322

