Babel无法解析"对于每个..."声明

时间:2018-05-25 18:54:11

标签: javascript babeljs demandware

我试图将Salesforce Commerce Cloud的.ds文件转换为JavaScript,以便我们可以应用标准测试工具(Jest,Mocha等)。 SFCC文档表明.ds文件是" Rhino JavaScript",具有类似Flow类型检查的非标准扩展。

到目前为止,使用transform-flow-strip-types插件删除类型注释很简单。但SFCC支持Babel窒息的弃用"for each...in" statement from JavaScript 1.6

以下所有代码均为available on github

这是我的源src / index.ds文件:

function dump(a: Array) {
    for each (var x in a) {
        console.log(x);
    }
}
module.exports = dump;

我的gulfile.js:

const gulp = require('gulp');
const babel = require('gulp-babel');

gulp.task('test', function () {
    gulp.src('src/**/*.ds')
        .pipe(babel())
        .pipe(gulp.dest('dst'));
});

这是我的package.json:

{
  "name": "dspoc",
  "version": "1.0.0",
  "description": "poc",
  "main": "index.ds",
  "author": "cjr",
  "license": "ISC",
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.26.3",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "gulp": "^3.9.1",
    "gulp-babel": "^7.0.1"
  },
  "babel": {
    "plugins": [
      "transform-flow-strip-types"
    ]
  }
}

当我运行gulp test时,我明白了:

%> gulp test
[11:23:06] Using gulpfile ~/dev/dspoc/gulpfile.js
[11:23:06] Starting 'test'...
[11:23:06] Finished 'test' after 9.15 ms

events.js:163
      throw er; // Unhandled 'error' event
      ^
SyntaxError: /Users/craser/dev/dspoc/src/index.ds: Unexpected token, expected ( (2:5)
  1 | function dump(a: Array) {
> 2 |   for each (var x in a) {
    |       ^
  3 |       console.log(x);
  4 |   }
  5 | }
    at Parser.pp$5.raise (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:4454:13)
    at Parser.pp.unexpected (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:1761:8)
    at Parser.pp.expect (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:1749:33)
    at Parser.pp$1.parseForStatement (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:2008:8)
    at Parser.pp$1.parseStatement (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:1836:19)
    at Parser.parseStatement (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:5910:22)
    at Parser.pp$1.parseBlockBody (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:2268:21)
    at Parser.pp$1.parseBlock (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:2247:8)
    at Parser.pp$3.parseFunctionBody (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:4235:22)
    at Parser.parseFunctionBody (/Users/craser/dev/dspoc/node_modules/babylon/lib/index.js:5897:20)

我花了不少时间挖掘一个插件,让Babel将其转换为类似for...of语句的内容,但我似乎找不到任何东西。

我现在正处于挖掘for-of transform的悬崖之中,并构建了类似于转换for each...in的东西,但我真的没有如果我可以避免它,我不得不把这项工作放进去。

我觉得我在这里遗漏了一些明显的东西。任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:2)

for each...in从未成为规范的官方部分,并且在Babel出现时并不存在,因此Babel不支持它。我担心在Babel能够处理之前,您必须更新该语法的所有用法。