babel-plugin-version

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

A Babel plugin that replaces occurrences of the string literal or identifier `__VERSION__` with the version string from `package.json` (e.g., `"0.2.3"`). Current stable version 0.2.3 enables compile-time version injection. The plugin can be configured to use a custom define name and to toggle replacement of identifiers vs. string literals. This is a lightweight zero-dependency tool for build processes using Babel for JavaScript/TypeScript projects.

error Error: Cannot find module 'babel-plugin-version'
cause The plugin is not installed as a dev dependency.
fix
Run: npm install --save-dev babel-plugin-version
error TypeError: Cannot read property 'replace' of undefined
cause The plugin cannot find a 'version' field in package.json.
fix
Ensure package.json exists in the Babel working directory and contains a 'version' string.
error error: unexpected token 'version' in babelrc
cause The plugin configuration array is incorrectly formatted.
fix
Use the correct nested array syntax: ['version', { options }] inside the plugins array.
gotcha The plugin only replaces `__VERSION__` (or custom define) when it appears as an identifier or string literal. It does NOT handle dynamic code or computed expressions.
fix Ensure __VERSION__ is used as a standalone identifier or a string literal (e.g., `const v = __VERSION__;` or `"__VERSION__"`).
gotcha The plugin reads the version from the nearest package.json file at compile time. If the working directory does not contain a package.json, the version will be undefined or empty string (depending on implementation).
fix Ensure that Babel runs in the context of your project root where package.json exists.
deprecated The plugin is still functional but deprecated in favor of using environment variables (e.g., process.env.npm_package_version) or define plugin (e.g., @rollup/plugin-replace) in modern builds.
fix Consider migrating to @rollup/plugin-replace for Rollup, or use DefinePlugin for webpack, or simply read process.env.npm_package_version at runtime if version is needed.
npm install babel-plugin-version
yarn add babel-plugin-version
pnpm add babel-plugin-version

A Babel plug-in that replaces __VERSION__ tokens with the version from package.json at build time.

// .babelrc or babel.config.js
{
  "plugins": [
    "version"
  ]
}

// Input: const appVersion = __VERSION__;
// Output: const appVersion = "0.2.3";
// The version is read from the nearest package.json at Babel transform time.