babel-plugin-remove-template-literals-whitespace
raw JSON → 1.0.4 verified Sat Apr 25 auth: no javascript
Babel plugin that strips leading/trailing whitespace and indentation whitespace from template literals at build time. Latest version 1.0.4 is stable, with infrequent releases. Key features: customizable whitespace removal via user-defined function, optional verbose logging. Differentiators: lightweight, focused solely on template literal whitespace, works with any Babel setup. Alternatives like babel-plugin-transform-template-literals or manual post-processing are heavier or require additional configuration. Suitable for minifying HTML templates or CSS-in-JS strings.
Common errors
error Error: Plugin/Preset files are not allowed to export objects, only functions. ↓
cause Using ES module import syntax in babel.config.js for this plugin (which is CJS-only).
fix
Use require('babel-plugin-remove-template-literals-whitespace') or string shorthand in plugins array.
error TypeError: Cannot read properties of undefined (reading 'replace') ↓
cause Custom 'fn' is not provided or returns undefined; plugin tries to call replace on result.
fix
Define fn as a function that returns a string. Example: (str) => str.trim()
Warnings
gotcha Custom function 'fn' receives the raw template literal string. It must handle all whitespace removal logic; no default removal is applied. ↓
fix Ensure your fn function removes all whitespace as needed, e.g., str.replace(/\s+/g, ' ')
gotcha Plugin only processes template literals that are direct children of a node (e.g., variable init, return). It does not process template literals inside JSX or other expressions. ↓
fix If using inside JSX, consider a JSX-specific plugin or manually wrap the template literal in a tagged template.
deprecated No deprecations recorded. Plugin is simple and stable.
Install
npm install babel-plugin-remove-template-literals-whitespace yarn add babel-plugin-remove-template-literals-whitespace pnpm add babel-plugin-remove-template-literals-whitespace Imports
- default wrong
import plugin from 'babel-plugin-remove-template-literals-whitespace'correctmodule.exports = require('babel-plugin-remove-template-literals-whitespace') - babel plugin usage wrong
plugins: ['babel-plugin-remove-template-literals-whitespace']correctplugins: ['remove-template-literals-whitespace'] - options wrong
plugins: [['remove-template-literals-whitespace', { trim: true }]]correctplugins: [['remove-template-literals-whitespace', { fn: (s) => s.trim() }]]
Quickstart
// babel.config.js
module.exports = {
plugins: [
['remove-template-literals-whitespace', {
fn: (str) => str.replace(/^\s+|\s+$/gm, '').replace(/\n\s*/g, '')
}]
]
};
// input.js
const html = `
<div>
<p>Hello</p>
</div>
`;
// output.js (after Babel transformation)
const html = `<div><p>Hello</p></div>`;