Minor improvements to block-scoping/tdz (#6782)

* Add test case for simple reference in tdz

* Add more examples from old issues as test cases

* Fix two testcases by excluding function declarations from being tdz checked

* Document the  option for block-scoping

* Add test cases with destructuring assignments

* Remove failing test cases

* [skip ci] Include type and default value for options
This commit is contained in:
Mauro Bringolf 2018-01-09 06:49:05 +01:00 committed by Logan Smyth
parent e9ed687666
commit 0a9f136d5f
16 changed files with 57 additions and 1 deletions

View File

@ -70,7 +70,10 @@ require("@babel/core").transform("code", {
});
```
## Options `throwIfClosureRequired`
## Options
### `throwIfClosureRequired`
`boolean`, defaults to `false`.
In cases such as the following it's impossible to rewrite let/const without adding an additional function and closure while transforming:
@ -81,3 +84,15 @@ for (let i = 0; i < 5; i++) {
```
In extremely performance-sensitive code, this can be undesirable. If `"throwIfClosureRequired": true` is set, Babel throws when transforming these patterns instead of automatically adding an additional function.
### `tdz`
`boolean`, defaults to `false`.
By default this plugin will ignore the *temporal dead zone (TDZ)* for block-scoped variables. The following code will **not throw an error when transpiled with Babel, which is not spec compliant**:
```javascript
i
let i;
```
If you need these errors you can tell Babel to try and find them by setting `"tdz": true` for this plugin. However, the current implementation might not get all edge cases right and its best to just avoid code like this in the first place.

View File

@ -38,6 +38,8 @@ export const visitor = {
const bindingPath = scope.getBinding(node.name).path;
if (bindingPath.isFunctionDeclaration()) return;
const status = getTDZStatus(path, bindingPath);
if (status === "inside") return;

View File

@ -0,0 +1,3 @@
f();
const f = function f() {}

View File

@ -0,0 +1,3 @@
{
"throws": "f is not defined - temporal dead zone"
}

View File

@ -0,0 +1 @@
let { b: d } = { d }

View File

@ -0,0 +1,3 @@
{
"throws": "d is not defined - temporal dead zone"
}

View File

@ -0,0 +1,5 @@
function f() {
x;
}
let x;
f();

View File

@ -0,0 +1,3 @@
f();
function f() {}

View File

@ -0,0 +1,3 @@
x = 3;
var x;

View File

@ -0,0 +1,3 @@
{
"plugins": [["transform-block-scoping",{"tdz": true}]]
}

View File

@ -0,0 +1 @@
let x = x;

View File

@ -0,0 +1,3 @@
{
"throws": "x is not defined - temporal dead zone"
}

View File

@ -0,0 +1,3 @@
var a = 5;
if (a){ console.log(a); let a = 2; }
console.log(a);

View File

@ -0,0 +1,3 @@
{
"throws": "a is not defined - temporal dead zone"
}

View File

@ -0,0 +1,2 @@
i
let i

View File

@ -0,0 +1,3 @@
{
"throws": "i is not defined - temporal dead zone"
}