React项目执行run serve时遭遇@babel/polyfill废弃错误的解决方案咨询
Hey there, let's resolve that annoying deprecation warning and get your app back on track. The error message gives us a clear path—we just need to replace the deprecated @babel/polyfill with explicit imports of core-js and regenerator-runtime, tailored to your existing Webpack setup. Here's how to do it step by step:
Step 1: Install Required Dependencies
First, add the packages that replace @babel/polyfill (since your config specifies corejs: 3, we'll install version 3 of core-js):
npm install core-js@3 regenerator-runtime --save # Or if you use Yarn: yarn add core-js@3 regenerator-runtime
Then, remove the deprecated package entirely:
npm uninstall @babel/polyfill # Yarn alternative: yarn remove @babel/polyfill
Step 2: Update Your Entry File (src/index.tsx)
Since your Babel config uses useBuiltIns: 'entry', you need to add the polyfill imports at the very top of your main entry file (before any other code):
// Replace any existing `import '@babel/polyfill'` with these lines import 'core-js/stable'; import 'regenerator-runtime/runtime'; // Rest of your index.tsx code follows... import React from 'react'; import ReactDOM from 'react-dom'; // ...your app initialization code
Step 3: Confirm Your Babel Config is Correct
Looking at your webpack.config.dev.js, your Babel preset-env setup is already aligned with the new polyfill approach:
{ presets: [ [ '@babel/preset-env', { useBuiltIns: 'entry', corejs: 3, }, ], ], }
Make sure this same configuration is present in your production webpack.config.js too, to keep consistency across environments.
Step 4: Quick Sanity Checks
- Ensure your
@babel/preset-envversion is 7.4.0 or higher—this is the first version that supports core-js@3. You can verify this by runningnpm list @babel/preset-envor checking yourpackage.json. - If you're using TypeScript, confirm your
tsconfig.jsonhas a reasonabletarget(e.g.,ES6or higher)—this helps avoid redundant polyfills and ensures smooth collaboration between TypeScript and Babel.
After making these changes, run your serve command again. The deprecation warning should disappear, and those related errors should be resolved.
内容的提问来源于stack exchange,提问作者Matt Hawes

