Babel should transform class private properties mixed with logical assignment operators
See original GitHub issueBug Report
This is a good first issue for first-time Babel contributors.
Current behavior A clear and concise description of the behavior.
throws
unknown: Property operator expected value to be one of ["+","-","/","%","*","**","&","|",">>",">>>","<<","^","==","===","!=","!==","in","instanceof",">","<",">=","<="] but got "??"
Input Code
class C {
#x;
m() { this.#x ??= 42 }
};
Expected behavior It should be transpiled successfully
Babel Configuration (babel.config.js, .babelrc, package.json#babel, cli command, .eslintrc)
- Filename:
babel.config.js
{
"presets": [
["@babel/preset-env", {
"targets": "Edge 16",
"shippedProposals": true
}]
],
"plugins": ["@babel/plugin-proposal-logical-assignment-operators"]
}
Environment CodeSandbox
Possible Solution
When transforming private class properties, babel will call packages/babel-helper-member-expression-to-functions/src/index.js
which transforms private property usage to helper calls. For example,
this.#x += 42
is approximately transformed to
_privateSet(this, x, _privateGet(this, x) + 42)
As you can see _privateGet(this, x) + 42
is a binary expression. But ??
is not a valid binary expression, so the error is thrown. To fix it, we should construct logical expression for logical assignment operators, namely ??=
, ||=
and &&=
.
If you don’t know how to clone Babel, follow these steps: (you need to have make
and yarn
available on your machine).
- Write a comment there to let other possible contributors know that you are working on this bug.
- Fork the repo
- Run
git clone https://github.com/<YOUR_USERNAME>/babel.git && cd babel
- Run
yarn && make bootstrap
- Wait ⏳
- Run
make watch
(ormake build
whenever you change a file) - Add a test (only
input.js
;output.js
will be automatically generated) topackages/babel-plugin-proposal-class-properties/test/fixtures/private/logical-assignment
(tip: you can copy from contents offixtures/private/assignment
) - Update the code!
yarn jest class-properties
to run the tests- If some test outputs don’t match but the new results are correct, you can delete the bad
output.js
files and run the tests again
- If some test outputs don’t match but the new results are correct, you can delete the bad
- If it is working, run
make test
to run all the tests - Run
git push
and open a PR!
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (7 by maintainers)
Specifically, this needs to be handled in https://github.com/babel/babel/blob/5b24d798758a9ad1f5aa383d1e83869ae7964ab1/packages/babel-helper-member-expression-to-functions/src/index.js#L287-L313
Thank you 💚