迁移至Babel 7 Beta后测试报错:需Babel ^7.0.0-0却加载6.26.0
Hey there, let's break down why you're hitting this "Requires Babel ^7.0.0-0, but was loaded with 6.26.0" error in your tests. The core issue is Jest is still trying to load the Babel 6.x version of babel-core, even though your project's fully migrated to Babel 7 Beta. Here's how to fix it step by step:
1. Install Jest Packages Compatible with Babel 7
Jest needs an updated babel-jest to work with Babel 7's renamed package structure (where babel-core became @babel/core). You already have the official bridge package babel-core@7.0.0-0 installed, but you might be missing the matching babel-jest version.
Run this to install the right packages:
npm install --save-dev babel-jest@^24.0.0 @babel/preset-env@^7.0.0-beta.49
Stick to versions that match your existing Babel Beta release to avoid mismatches.
2. Update Jest Config to Point to Babel 7
Tell Jest explicitly to use babel-jest and recognize your Babel 7 setup by adding a transform block to your jest.config.js:
module.exports = { rootDir: '<rootDir>/../../', collectCoverageFrom: ['src/**/*.(jsx|js)'], moduleNameMapper: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/tests/fileMock.js', }, setupTestFrameworkScriptFile: '<rootDir>/tests/setupTests.js', // Add these lines transform: { '^.+\\.(js|jsx)$': 'babel-jest', }, transformIgnorePatterns: [ '/node_modules/' ], };
3. Clear Caches & Reinstall Dependencies
Old cached packages are often the culprit here. Let's wipe them out:
- Delete your
node_modulesfolder:rm -rf node_modules(usermdir /s /q node_moduleson Windows) - Remove your lock file:
rm package-lock.json(oryarn.lockif you use Yarn) - Reinstall dependencies:
npm install - Clear Jest's cache:
jest --clearCache
4. Verify babel-plugin-module-resolver Compatibility
Your config uses babel-plugin-module-resolver@3.1.1 which supports Babel 7, but updating to the latest version can rule out any edge cases:
npm update babel-plugin-module-resolver --save-dev
5. Test with No Cache (Temporary)
Add the --no-cache flag to your test command to bypass any leftover cached data while troubleshooting:
"test": "jest --no-cache --config tests/jest.config.js",
After going through these steps, run your tests again—this should resolve the version mismatch and get your test suites passing.
内容的提问来源于stack exchange,提问作者Tomasz Mularczyk

