Vue-CLI v3+Jest环境下import语句加分号报错求助
Wow, that's a super weird quirk you've run into—adding a semicolon to your import statements breaking Jest with an Unexpected token import error? Total head-scratcher. Let's break down what's likely going on here and how to fix it, based on your project setup:
What's Probably Causing This
This issue almost certainly stems from a compatibility hiccup between Babel and Jest's transpilation pipeline, specifically how babel-jest processes your code. Your project uses babel-core@7.0.0-bridge.0 to bridge Babel 7 and Jest, and it seems this bridge is tripping up when it encounters semicolons at the end of import statements—failing to properly transpile the ES module syntax to something Jest can understand.
Fixes to Try
1. Update Babel-Jest to a Version Compatible with Babel 7
Your current babel-jest version (23.6.0) is a bit outdated for Babel 7. Let's get it aligned:
- Uninstall the old version first:
npm uninstall babel-jest - Install a compatible version (match it to your Vue-CLI 3.x setup—24.x works well):
npm install babel-jest@^24.9.0 --save-dev
Or just update all your dev dependencies to their latest compatible versions:
npm update --save-dev
2. Tweak Jest's Transform Configuration
Your existing Jest transform rule for JS/JSX might not be handling semicolon-terminated imports correctly. Let's add a Babel option to force proper module detection:
In your package.json's jest section, modify the transform entry like this:
"transform": { "^.+\\.vue$": "vue-jest", ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub", "^.+\\.jsx?$": ["babel-jest", { "sourceType": "unambiguous" }] }
The sourceType: "unambiguous" flag tells Babel to automatically detect whether a file is an ES module or a script, which should eliminate the semicolon-related misinterpretation.
3. Ensure Your Babel Config is Correct
If you don't already have one, create a babel.config.js file in your project root with the Vue-CLI default preset—this ensures Babel is transpiling your code the way Vue expects:
module.exports = { presets: [ '@vue/app' ] }
If you do have a Babel config, double-check it doesn't have any custom rules that might be interfering with import statement processing.
4. Temporary Workaround: Adjust ESLint to Avoid Semicolons (Not Ideal)
If you need a quick fix while sorting out the transpilation issue, you can have ESLint automatically remove semicolons from imports. Add this rule to your eslintConfig.rules in package.json:
"rules": { "semi": ["error", "never"] }
Again, this is just a band-aid—fixing the transpilation issue is the better long-term solution.
Verify the Fix
After making any of these changes, run your tests again to confirm:
npm run test:unit
Your semicolon-terminated imports should now work without throwing that Unexpected token import error.
内容的提问来源于stack exchange,提问作者TheLinuxPro

