babel-plugin-optimize-obj-str
raw JSON → 1.0.0 verified Sat Apr 25 auth: no javascript
Babel plugin that optimizes calls to `obj-str` by replacing them with equivalent unrolled string concatenation, resulting in ~1.8x performance improvement. Version 1.1.0 includes TypeScript definitions. Maintained by the same author as the `obj-str` library. Key differentiator: unlike other classname utilities, this plugin performs static analysis to inline only optimizable calls, preserving others by default. Released under MIT license.
Common errors
error Module not found: Error: Can't resolve 'babel-plugin-optimize-obj-str' ↓
cause Forgot to install the plugin.
fix
npm install --save-dev babel-plugin-optimize-obj-str
error TypeError: Cannot read property 'replace' of undefined ↓
cause Passing an argument that is not an object literal (e.g., identifier, spread).
fix
Ensure the first argument to objstr() is an object literal with string literal keys. Non-optimizable calls are preserved by default.
Warnings
gotcha Transformed output includes a leading space for truthy values, unlike raw objstr() which omits leading spaces. Ensure consumers handle leading spaces. ↓
fix The leading space is intentional; most consumers like className work fine with it.
gotcha Duplicate property names with identical keys are resolved by the last value, but the plugin uses the first key's literal string. If duplicate keys have different conditions, the behavior may be unexpected. ↓
fix Avoid duplicate keys in obj-str calls, or use a consistent condition for duplicate keys.
gotcha The plugin may slightly increase bundle size if many (e.g., >100) conditional properties are used. It is intended for performance, not size reduction. ↓
fix Consider the trade-off; for large number of properties, using obj-str directly may be smaller.
deprecated The option 'strict' defaults to false. Setting strict: true makes the plugin throw errors for non-optimizable calls, which may break builds. ↓
fix Use strict mode only if you have full control over all obj-str calls and want to enforce optimization.
Install
npm install babel-plugin-optimize-objstr yarn add babel-plugin-optimize-objstr pnpm add babel-plugin-optimize-objstr Imports
- plugin wrong
plugins: ['babel-plugin-optimize-obj-str']correctplugins: ['optimize-obj-str'] - options wrong
plugins: ['optimize-obj-str', { strict: true }]correctplugins: [['optimize-obj-str', { strict: true }]]
Quickstart
// babel.config.js
module.exports = {
plugins: ['optimize-obj-str']
};
// input.js
import objstr from 'obj-str';
const classes = objstr({
'btn': true,
'btn-primary': isPrimary,
'disabled': isDisabled
});
// output.js
const classes = 'btn' + (isPrimary ? ' btn-primary' : '') + (isDisabled ? ' disabled' : '');