为什么在nodejs中传播语法引发错误

时间:2018-12-21 05:15:26

标签: javascript node.js reactjs object

我正在使用此代码创建文档。哪个按预期工作。

await Promise.all(
  payload.exercises.map(async(exercise) => {
      exercise.user = user
      exercise.workoutName = payload.workoutName
      await Exercise.create(exercise)
  })
)

但是要优化代码,我想对exercise对象使用传播语法

await Promise.all(
  payload.exercises.map(async(exercise) => {
      await Exercise.create({ ...exercise, user, workoutName: payload.workoutName })
  })
)

但是当我编译它时,它会引发错误Unexpected token (58:36)

有人可以帮忙,为什么我不能在后端使用它,而只能在前端reactjs

使用

.babelrc文件

{
  "presets": [
    ["env", {
      "targets": {
        "node": "11.5.0"
      }
    }]
  ],
  "env": {
    "test": {
      "plugins": ["istanbul"]
    }
  }
}

package.json

{
  "main": "index.js",
  "scripts": {
    "start:dev": "nodemon ./src/index.js",
    "start": "npm run build && node ./build/index.js",
    "build": "babel src -d build -s --source-maps --copy-files",
    "seed": "babel-node ./seeders/index.js",
  },
  "dependencies": {
    "@sendgrid/mail": "^6.2.1",
    ...
  },
  "devDependencies": {
    "async": "2.3.0",
    "babel-cli": "6.24.0",
    "babel-core": "6.24.0",
    "babel-eslint": "7.2.1",
    "babel-plugin-istanbul": "4.1.1",
    "babel-polyfill": "6.23.0",
    "babel-preset-env": "^1.2.2",
    "babel-preset-node6": "11.0.0",
    "chalk": "1.1.3",
    "chance": "1.0.6",
    "eslint": "3.19.0",
    "eslint-config-walmart": "1.2.2",
    "eslint-plugin-filenames": "1.1.0",
    "eslint-plugin-import": "2.2.0",
    "lab-babel": "1.1.1",
  }
}

1 个答案:

答案 0 :(得分:2)

坦率地说:我不太确定Babel v6中的Babel配置是什么问题。尽管我认为所有命名更改都可以解决该问题,但npm模块可能与从v6到v7的转换有关。我不再使用Babel v6。

复制您的问题后,我已经可以使用Babel v7解决它。方法如下:

  1. 我从devDependencies的{​​{1}}中删除了所有通天币条目,所以看起来像这样:

    package.json
  2. 已完全删除"devDependencies": { "async": "2.3.0", "chalk": "1.1.3", "chance": "1.0.6", "eslint": "3.19.0", "eslint-config-walmart": "1.2.2", "eslint-plugin-filenames": "1.1.0", "eslint-plugin-import": "2.2.0", "lab-babel": "1.1.1" }

  3. 重新创建的node_modules

    npm install
  4. 已安装Babel v7 (不幸的是,声称适用于v7.1.0的当前文档的CLI安装行不正确,我filed an issue:< / p>

    npm install --save-dev @babel/core @babel/cli @babel/preset-env

    ...这给了我这些node_modules

    devDependencies
  5. 确保"devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.2.2", "@babel/preset-env": "^7.2.3", "async": "2.3.0", "chalk": "1.1.3", "chance": "1.0.6", "eslint": "3.19.0", "eslint-config-walmart": "1.2.2", "eslint-plugin-filenames": "1.1.0", "eslint-plugin-import": "2.2.0", "lab-babel": "1.1.1" } 已设置为使用新的.babelrc

    @babel/env

然后,{ "presets": [ ["@babel/env", { targets: { "node": "11.5.0" } }] ], "env": { "test": { "plugins": ["istanbul"] } } } 正常工作。传播语法被保留了下来(因为Node v11.5.0本身就支持它)。

可以肯定的是,由于您的问题的较早版本使用npm run build"node": 4.3应该用引号引起来,顺便说一句),因此我改用了它,并且效果很好,转换了传播语法(以及4.3 / async和许多其他内容,因为Node.js v4.3确实已过时)。