React应用遭遇Module parse failed: Unexpected token错误,headers-polyfill模块解析失败寻求解决方案
Hey there, let's work through this error you're hitting. That Unexpected token issue in /node_modules/headers-polyfill/lib/Headers.js happens because your build tool (probably webpack) can't process the modern JavaScript syntax the library uses—specifically the class instance field syntax you highlighted: [NORMALIZED_HEADERS] = {};.
Here are the actionable steps to fix this:
Update your Babel configuration to handle class fields
The[NORMALIZED_HEADERS] = {}line uses ES2022 class instance fields, which older Babel presets might not support out of the box. Add the class properties plugin to your Babel config:{ "presets": ["@babel/preset-react", "@babel/preset-env"], "plugins": ["@babel/plugin-proposal-class-properties"] }If you're using
@babel/preset-env, make sure it's configured to target environments that support this syntax, or let it automatically handle polyfills withuseBuiltIns: 'usage'.Tell webpack to transpile the headers-polyfill package
By default, webpack skips transpiling mostnode_modulespackages. Butheaders-polyfilluses untranspiled modern syntax, so you need to include it in your babel-loader processing:// In your webpack.config.js module.exports = { // ... other config module: { rules: [ { test: /\.js$/, // Exclude all node_modules except headers-polyfill exclude: /node_modules\/(?!headers-polyfill)/, use: 'babel-loader' } ] } };Update your build dependencies
Outdated versions of Babel or webpack might lack support for newer JS features. Run these commands to get the latest stable versions:npm update @babel/core @babel/preset-env babel-loader webpackIf you're using Create React App (CRA)
CRA hides the webpack/Babel config by default. You can either:- Eject your app with
npm run eject(irreversible), then modify the config as above. - Use
react-app-rewiredto override the config without ejecting. Create aconfig-overrides.jsfile with:
Then update yourmodule.exports = function override(config) { // Adjust the JS rule to include headers-polyfill config.module.rules[1].oneOf.forEach(rule => { if (rule.test.test('.js')) { rule.exclude = /node_modules\/(?!headers-polyfill)/; } }); return config; };package.jsonscripts to usereact-app-rewiredinstead ofreact-scripts.
- Eject your app with
The root cause here is that your build pipeline isn't set up to handle the modern class syntax used by headers-polyfill. Once you adjust your configs or update dependencies to transpile that syntax, the error should go away.
内容的提问来源于stack exchange,提问作者Vivek Singh

