babel-plugin-inline-constants

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

Babel plugin (v5.0.0) to inline constant values from imported modules. Supports ESM (import) and CJS (require). Evaluates specified modules with Node to retrieve primitive values (numbers, strings, booleans, null) and replaces references directly in code for better gzip compression. TypeScript types included, ESM-only, Node 18+. Similar to babel-plugin-transform-define but focuses on module-exported constants.

error Error: Cannot find module 'babel-plugin-inline-constants'
cause Package not installed or installed as devDependency incorrectly.
fix
Run: npm install --save-dev babel-plugin-inline-constants
error TypeError: inlineConstants is not a function
cause Using require on ESM-only module.
fix
Use import or ensure you are in an ESM context.
error Error: babel-plugin-inline-constants: missing required option 'modules'
cause No modules option provided to the plugin.
fix
Example: { "plugins": [["babel-plugin-inline-constants", { "modules": ["./constants.js"] }]] }
error Error: Cannot read properties of undefined (reading 'some')
cause Trying to inline a non-primitive export like an object or function.
fix
Only export primitives (numbers, strings, booleans, null) from constant modules.
error Module not found: Can't resolve './my-constants'
cause Path resolution issue; module path relative to cwd.
fix
Ensure module path is correct relative to the Babel working directory.
breaking Dropped support for Node 16.
fix Upgrade to Node 18+.
breaking Migration to ESM-only. No CommonJS support.
fix Use import syntax or dynamic import().
gotcha Modules are evaluated with Node, so only use the plugin if you trust the code.
fix Do not inline untrusted modules.
gotcha The modules option is required; omitting it throws an error.
fix Always specify modules in plugin options.
gotcha Only primitives (numbers, strings, booleans, null) are inlined. Objects, arrays, functions are not supported.
fix Ensure constants are primitives.
npm install babel-plugin-inline-constants
yarn add babel-plugin-inline-constants
pnpm add babel-plugin-inline-constants

Shows how to configure the plugin with a modules list, and how constants are inlined in the output.

// .babelrc
{
  "plugins": [["babel-plugin-inline-constants", { "modules": ["./constants.js"] }]]
}

// constants.js
export const SITE = 'example.com';
export const PORT = 8080;

// input.js
import { SITE, PORT } from './constants.js';
console.log(`https://${SITE}:${PORT}`);

// output (after babel)
console.log(`https://example.com:8080`);