为什么速记分配在我的 babel 设置中不起作用?

Why does short-hand assignment not work in my babel setup?

背景

我目前正在通过 babel 将我的项目后端迁移到 ES6,我 运行 遇到了一个似乎与不再有效的速记分配有关的错误?我对通天塔不熟悉。可能是我在这里没有看到非常明显的东西。

问题

现在,当我尝试通过 yarn start 在开发中 运行 我的应用程序时,我看到以下错误(简化示例)这在设置 babel 之前确实有效(我在 node.js 13.13.0).知道这里发生了什么吗?

代码段:

const a = {
  hi:1, bye:2, ciao: 3
}
const b  = {hi, bye} = a
console.log(b)

错误信息:

[nodemon] restarting due to changes...
[nodemon] starting `NODE_ENV=development babel-node server.js server.js`
/Users/user/Projects/fb/fb-flow-app/server/config/config.js:21
var b = (_a = a, hi = _a.hi, bye = _a.bye, _a);
                    ^

ReferenceError: hi is not defined
    at Object.<anonymous> (/Users/user/Projects/fb/fb-flow-app/server/config/config.js:12:8)
    at Module._compile (internal/modules/cjs/loader.js:1123:30)
    at Module._compile (/Users/user/Projects/fb/fb-flow-app/server/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
    at Object.newLoader [as .js] (/Users/user/Projects/fb/fb-flow-app/server/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:972:32)
    at Function.Module._load (internal/modules/cjs/loader.js:872:14)
    at Module.require (internal/modules/cjs/loader.js:1012:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/Users/user/Projects/fb/fb-flow-app/server/server.js:1:14)
[nodemon] app crashed - waiting for file changes before starting...

高级项目结构:

root
|-frontend
|-server

前端是一个 next.js 项目并且有它自己的 .babelrc 似乎在工作。

到目前为止采取的步骤

我已经安装了几个 babel-dev-dependencies(在我的服务器文件夹中):

"devDependencies": {
    "@babel/cli": "^7.10.1",
    "@babel/core": "^7.10.2",
    "@babel/node": "^7.10.1",
    "@babel/preset-env": "^7.10.2",
    ...
}

也试过了(没有结果)

@babel/plugin-transform-shorthand-properties
@babel/plugin-transform-spread

我已经配置了 nodemon.json:

{
    "watch": ["../server"],
    "exec": "NODE_ENV=development babel-node server.js",
    "ext": "js"
}

我设置了一个.babelrc

{
    "presets": ["@babel/preset-env"]
}

然后我运行宁通过:

"scripts": {
    "start": "concurrently --prefix none \"cd server && NODE_ENV=development yarn nodemon server.js\" \"cd frontend && yarn dev\""
},

当您执行以下操作时:

const a = {
  hi:1, bye:2, ciao: 3
}
const b  = {hi, bye} = a

Babel 看到对两个变量的赋值,名为 hibye 尚不存在。 Babel 似乎在 strict mode 中运行,这是一个错误。在严格模式下,您将在 Node 中获得相同的结果。通过明确定义它们来解决这个问题:

const a = {
  hi:1, bye:2, ciao: 3
}
let hi, bye;
const b  = {hi, bye} = a

解构不会生成对象,尽管它看起来 像对象初始化。

请注意,因此,b 的值是 而不是 一个看起来像 {hi:1, bye:2} 的对象,而是对 [=17= 的引用], 就像你做 const b = a:

会发生什么
const b = a;
a.hi = 5;
console.log(b.hi); // 5

您可以做的其他事情:

  • const {hi, bye} = a; 得到两个名为 hibye 的常量变量(而不是 varlet
  • const {hi: b, bye: c} = a; 得到两个名为 bc ("renaming")
  • const {hi, bye} = a; const b = {hi, bye}; 使用变量 b 中的这两个键创建一个对象,但这也会创建变量 hibye.