React、Standard与ESLint报错:'propTypes'等未定义问题求助
Hey there, let's work through this issue you're hitting. Those no-undef errors pop up because ESLint (via Standard) isn't properly recognizing the static class fields syntax you're using for propTypes and defaultProps. Even though you've got the Babel plugin installed, the configuration pieces aren't fully aligned. Here's how to fix it step by step:
1. Set Up Your Babel Configuration Correctly
First, make sure you have a .babelrc file in your project root that explicitly enables the class properties plugin. Installing the plugin isn't enough—Babel needs to know to use it:
{ "plugins": ["@babel/plugin-proposal-class-properties"] }
This tells Babel (and babel-eslint, which ESLint uses) to parse static class fields properly, so ESLint won't mistake propTypes and defaultProps for undefined variables.
2. Double-Check Your Standard Configuration in package.json
Confirm your package.json has the correct setup pointing to babel-eslint as the parser. It should look exactly like this (you already have this, but a quick sanity check never hurts):
{ "standard": { "parser": "babel-eslint" } }
Watch out for typos or missing commas—small syntax errors here can break the whole setup.
3. Fix Dependency Compatibility
Your versions of babel-eslint (8.2.3) and @babel/plugin-proposal-class-properties (7.0.0-beta.40) are a bit mismatched. Babel 7's beta versions can have quirks with older babel-eslint releases. Try upgrading babel-eslint to a version that plays nicely with your Babel plugin:
Run this in your terminal if you use npm:
npm install babel-eslint@^10.0.0 --save-dev
Or if you use Yarn:
yarn add babel-eslint@^10.0.0 --dev
Version 10.x of babel-eslint is built for Babel 7's stable plugins, which should iron out any parsing inconsistencies.
4. Quick Fallback: Use Traditional Static Property Assignment
If you don't want to mess with dependency upgrades right now, you can switch to the classic way of defining propTypes and defaultProps outside the class. ESLint will recognize this syntax immediately:
class MyComponent extends React.Component { myMethod = () => {} render () {} } MyComponent.propTypes = {}; MyComponent.defaultProps = {};
It's a temporary fix that avoids configuration headaches, even if it doesn't use the class fields syntax you prefer.
After trying these steps, restart VS Code (or just the ESLint server) to make sure the changes take effect. Those no-undef errors should be gone!
内容的提问来源于stack exchange,提问作者Stephen Last

