babel-plugin-transform-globalthis

raw JSON →
1.0.0 verified Sat Apr 25 auth: no javascript

Babel plugin that transforms `globalThis` references to a ponyfill detecting the runtime environment (window, self, global, or fallback object). Version 1.0.0 released Jan 2021; single stable release with no further updates. Differentiates from @babel/plugin-transform-global-this by not relying on core-js and providing a lighter-weight transformation. Suitable for environments where globalThis is unsupported or for projects that prefer explicit polyfilling via Babel transpilation.

error SyntaxError: Unexpected token 'export'
cause Using ESM import syntax in .babelrc.js or babel.config.js while plugin is CJS
fix
Use module.exports or .babelrc JSON format; e.g., module.exports = { plugins: ['babel-plugin-transform-globalthis'] };
error ReferenceError: globalThis is not defined
cause Plugin not applied (transpilation skipped or Babel not configured)
fix
Ensure Babel is configured to run on the file where globalThis appears; add plugin to .babelrc or babel.config.json.
gotcha Plugin uses RUNTIME ponyfill inserted inline, not a shared module. Increases bundle size if globalThis used in many files.
fix Use @babel/plugin-transform-global-this or core-js for shared polyfill; or use module-level plugin to avoid duplication.
gotcha Transformation is applied only to direct globalThis references; not to property accesses on global objects like window.
fix Ensure all cross-environment code uses globalThis explicitly; the plugin does not transform window, self, or global.
gotcha No option to customize the ponyfill variable name; always uses _globalThis.
fix Accept the generated variable name; or fork the plugin to add configuration.
npm install babel-plugin-transform-globalthis
yarn add babel-plugin-transform-globalthis
pnpm add babel-plugin-transform-globalthis

Shows basic setup using .babelrc and transformation of globalThis to a runtime-detected global object.

// Install: npm install --save-dev babel-plugin-transform-globalthis
// .babelrc
{
  "plugins": ["babel-plugin-transform-globalthis"]
}
// Input
const x = globalThis.Math;
// Output (ES5-compatible ponyfill)
var _globalThis = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : {};
var x = _globalThis.Math;