What is @babel/plugin-transform-typeof-symbol?
The @babel/plugin-transform-typeof-symbol package is a plugin for Babel, a JavaScript compiler, that ensures the behavior of the 'typeof' operator is spec-compliant when used with symbols. In environments that do not fully support symbols, this plugin transforms 'typeof' checks to a method that can correctly identify 'symbol' types.
What are @babel/plugin-transform-typeof-symbol's main functionalities?
Transform typeof checks for symbols
This code represents the transformation that the plugin applies to 'typeof' checks. It defines a function that can correctly identify symbols, even in environments that do not natively support the 'symbol' type.
var _typeof = function(obj) { return obj && typeof Symbol !== 'undefined' && obj.constructor === Symbol ? 'symbol' : typeof obj; };
Other packages similar to @babel/plugin-transform-typeof-symbol
@babel/plugin-transform-runtime
This package helps to reuse Babel's injected helper code to save on codesize. It includes a typeof helper for symbols, similar to what @babel/plugin-transform-typeof-symbol provides, but it's part of a broader set of transformations.
core-js
Although not a direct alternative, core-js is a modular standard library for JavaScript, which includes polyfills for symbols. It ensures that 'typeof' checks for symbols work correctly in older environments, similar to the goal of @babel/plugin-transform-typeof-symbol.
@babel/plugin-transform-typeof-symbol
ES6 introduces a new native type called symbols. This transformer wraps all typeof
expressions with a method that replicates native behaviour. (ie. returning "symbol" for symbols)
Example
In
typeof Symbol() === "symbol";
Out
var _typeof = function (obj) {
return obj && obj.constructor === Symbol ? "symbol" : typeof obj;
};
_typeof(Symbol()) === "symbol";
Installation
npm install --save-dev @babel/plugin-transform-typeof-symbol
Usage
Via .babelrc
(Recommended)
.babelrc
{
"plugins": ["@babel/transform-typeof-symbol"]
}
Via CLI
babel --plugins @babel/transform-typeof-symbol script.js
Via Node API
require("@babel/core").transform("code", {
plugins: ["@babel/transform-typeof-symbol"]
});