What is "loose" mean in Babeljs?

Viewed 348

Very often, reading the documentation for Babel and his plugins, I meet loose option. I have not seen a good enough example to understand what it is.

Here is an example in preset-es2015 documentation.

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

Can someone explain in details that this option does?

1 Answers

This article is the best example on the web at the moment. I advise you to read this article, it explained example of the plugin babel-plugin-transform-es2015-class.

Below I will give an example of another plugin babel-plugin-transform-es2015-for-of.

Source code:

for (var i of foo) {}

loose: false - generated code is obtained the most strict and compatible with the standard, with a lot of checks.

var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = foo[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var i = _step.value;
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

loose: true - lighter version, which follow specification less, but produce the same result.

for (var _iterator = foo, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  var _ref;

  if (_isArray) {
    if (_i >= _iterator.length) break;
    _ref = _iterator[_i++];
  } else {
    _i = _iterator.next();
    if (_i.done) break;
    _ref = _i.value;
  }

  var i = _ref;
}
Related