albertogasparin / react-magnetic-di

Dependency injection and replacement for Javascript and React components/hooks
MIT License
131 stars 7 forks source link

fix: handle temporal deadzone for local variables shadowing parent function #91

Closed theKashey closed 2 months ago

theKashey commented 3 months ago

Consider the following code:

function token(path) {
    let token = tokens[path];
}

right now it will be converted into

function token(path, fallback) {
  const [_tokens] = (0, _reactMagneticDi.di)([_tokenNames.default], token);
  let token = _tokens[path];
}

However, due to let token we will face the temporal dead zone or "cannot access token before initialization"


This PR just handles this moment by removing scope when such case is detected.

albertogasparin commented 3 months ago

Ouch! Thanks for finding this edge case. I guess I've never seen in our projects thanks to no-shadow being enforced.

theKashey commented 3 months ago

It was never seen around because we usually transpile everything down to var. Which is not a bad idea, by removing TDZ you make some things faster.

unction token(path, fallback) {
  var [_tokens] = (0, _reactMagneticDi.di)([_tokenNames.default], token);
  var token = _tokens[path];
}

in this case, it would not be an error, but token will be undefined as it still placed before initialization.

theKashey commented 2 months ago

CI builds may be green, but tests on local fail. @albertogasparin - can you verify how the current solution works for you and on your machine 🙏

albertogasparin commented 2 months ago

After running npm i the test passes in local too. Must be some Babel package update. Might do a global bump soon

theKashey commented 2 months ago

🤔 npm, not yarn