javascript - Babelifying JavaScript Module Pattern with ES6 Arrow Functions
问题描述
Babel is choking on code that uses the module pattern with an arrow function.
If I try to process a file which reads:
const lib = (() => {
function sum(a, b) { return a + b; }
function mult(a, b) { return a * b; }
return {
sum,
mult
};
}());
Babel gives a SyntaxError
{ SyntaxError: /home/david/Sync/ebs/office/fake.js: Unexpected token, expected "," (9:1)
7 | mult
8 | };
> 9 | }());
| ^
10 |
at Parser.raise (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:3939:15)
at Parser.unexpected (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5248:16)
at Parser.expect (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5236:28)
at Parser.parseParenAndDistinguishExpression (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:6454:14)
at Parser.parseExprAtom (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:6284:21)
at Parser.parseExprSubscripts (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5924:21)
at Parser.parseMaybeUnary (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5903:21)
at Parser.parseExprOps (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5812:21)
at Parser.parseMaybeConditional (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5784:21)
at Parser.parseMaybeAssign (/home/david/Sync/ebs/office/node_modules/@babel/parser/lib/index.js:5731:21)
pos: 137,
loc: Position { line: 9, column: 1 },
code: 'BABEL_PARSE_ERROR' }
However, if I change the code to use an older style function, like
const lib = (function () {
function sum(a, b) { return a + b; }
function mult(a, b) { return a * b; }
return {
sum,
mult
};
}());
Babel seems to process the file with no issues.
What am I doing wrong? Is there a genuine syntax problem with the arrow function code I am not aware of?
解决方案
由于箭头函数的性质以及它们的解释方式,(例如:
const x = () => ({ objectPropValues });
const x = () => { functionBody };
const x = () => conciseFunctionBody;
我想第二个箭头功能在
const x = (() => {functionBody})();
const x = (() => {functionBody}());
不能被允许,也不能。
这可以通过仔细查看 ECMA 6 的箭头函数规范来确认。
推荐阅读
- angular5 - 当我在角度为 5 的其他下拉列表中选择不同的列表值时,下拉列表更改列表值
- docker - 官方 Docker 初学者教程上的 Docker 卷与持久卷
- optimization - 获取一组行的最优化方法是什么,这些行出现在 java 8 的列表中间?
- ssas - SSAS,如何使维度属性月仅显示当年的月份?
- android - TTS 工作一分钟后停止说话
- java-8 - 转换 Flux 时卡住了
到单声道 ? - javascript - 百万行表(Web 开发)
- beautifulsoup -
使用 beautifulsoup 从 html 解析数据中提取记录 - create-react-app - 卸载 Expo CLI
- arrays - 无法在 Swift 4.2 中将类型“[UITableViewCell.Type]”的值转换为“[_.Type]”