为何声明App类静态字段cart时JSHint抛出E054错误?
Hey there! Let's break down why you're getting that error and how to fix it.
The Root Cause
Your code uses ES2022+ static class field syntax (static cart;), but JSHint's default configuration doesn't enable support for this newer JavaScript feature. Older versions of the ECMAScript standard only allowed methods inside classes, so JSHint is throwing an error because it doesn't recognize the static field declaration as valid syntax yet.
Solutions to Fix the Error
1. Update JSHint Configuration to Support Modern JS
The easiest way to fix this is to tell JSHint to use a newer ES version. Here's how:
- Create a
.jshintrcfile in your project's root directory (if you don't have one already). - Add the following JSON to enable ES2022 support:
ES2022 corresponds to{ "esversion": 13 }esversion 13—this will let JSHint recognize static class fields as valid syntax.
2. Use the Older Syntax for Static Properties
If you don't want to modify the JSHint config, you can declare the static property outside the class instead:
class App { static init() { const shop = new Shop(); shop.render(); this.cart = shop.cart; } } // Declare static property outside the class App.cart; // Or initialize it with a default value like App.cart = null;
This was the standard way to add static properties before ES2022, and JSHint will recognize this without extra configuration.
3. Verify VSCode JSHint Plugin Settings
Sometimes VSCode might not pick up your .jshintrc file automatically. To check:
- Open VSCode settings (Ctrl/Cmd + ,)
- Search for
jshint.config - Make sure the path points to your project's
.jshintrcfile (if it's not already set to auto-detect)
Quick Note for New JS Developers
Using the first solution (updating JSHint's ES version) is recommended because it aligns with modern JavaScript practices. Once you set up the .jshintrc file, you'll be able to use other modern features like arrow functions, optional chaining, etc., without similar errors.
内容的提问来源于stack exchange,提问作者pospolitaki

