ES6箭头函数转ES5:AngularJS项目Gulp+Esprima校验报错求助
Got it, let's tackle this problem head-on. The error you're seeing is because your version of Esprima doesn't support ES6 arrow functions—those => syntax bits are throwing it off. Here's how to convert your code to ES5 syntax so it passes the lint check, plus some extra context to avoid this in the future.
Step 1: Convert the Arrow Functions to ES5 function Declarations
Your original ES6 code uses arrow functions for both filter and findIndex callbacks. Let's rewrite each one with standard ES5 function syntax, adding explicit return statements since arrow functions omit them for single-line expressions:
Original ES6 Code:
var filteredCampaignItems = campaignItems.filter((thing, index, self) => index === self.findIndex((t) => ( t.expectedAdvertisementDisplayCount === thing.expectedAdvertisementDisplayCount && t.smartId === thing.smartId )) )
Converted ES5 Code:
var filteredCampaignItems = campaignItems.filter(function(thing, index, self) { return index === self.findIndex(function(t) { return t.expectedAdvertisementDisplayCount === thing.expectedAdvertisementDisplayCount && t.smartId === thing.smartId; }); });
Why This Works
Esprima (especially older versions) was built to validate ES5 syntax first. Arrow functions are an ES6 feature, so the parser doesn't recognize the => token—hence the "Unexpected identifier" error. By switching to traditional function declarations and adding explicit return statements, you're giving Esprima syntax it understands fully.
Bonus: Future-Proof Your Workflow
If you want to keep writing ES6 code without manual conversions every time, you have two solid options:
- Upgrade Esprima: Check for a newer version of Esprima—many recent releases support ES6 syntax natively.
- Add Babel to Your Gulp Pipeline: Insert a Babel transpilation step before Esprima validation. This will automatically convert your ES6 code to ES5, letting you use modern syntax while maintaining compatibility with ES5-only tools.
内容的提问来源于stack exchange,提问作者Arter

