Plugins and JavaScript
A plugin is a JavaScript module that extends Less: it adds functions, post-processes the result or changes how files are found. The built-in functions cover most tasks, but sometimes you need your own — for example, converting pixels to rem with one function. Sass lets you write such functions in Sass itself with @function; in Less a function is written in JavaScript.
Your own function
Create the file styles/plugins/rem.js. The install function receives the less object and the functions registry:
// styles/plugins/rem.js
module.exports = {
install(less, pluginManager, functions) {
functions.add('rem', (px) => new less.tree.Dimension(px.value / 16, 'rem'));
},
};less.tree.Dimension is a number with a unit as Less sees it. The function takes a value in pixels, divides it by 16 and returns rem.
Loading with @plugin
The @plugin directive loads the file relative to the current .less file; the .js extension can be left out:
// styles/main.less
@plugin "plugins/rem";
.title {
font-size: rem(24px);
margin-bottom: rem(8px);
}.title {
font-size: 1.5rem;
margin-bottom: 0.5rem;
}<style>
.title {
font-size: 1.5rem;
margin-bottom: 0.5rem;
}
</style>
<h1 class="title">A new post</h1>
<p>The heading is 1.5rem, that is 24px at the normal font size.</p>The latest Less 4 versions print a warning here: the @plugin directive will be replaced in Less 5. The CSS is built as usual, but keep your plugins in one place so they are easy to move later.
Ready-made plugins from npm
Many plugins are published on npm with names like less-plugin-... and are enabled with a command-line flag. For example, minifying the CSS:
npm install --save-dev less-plugin-clean-css
npx lessc --clean-css styles/main.less css/main.min.csscss/main.min.css will contain CSS without spaces and line breaks — for publishing. In a Vite project Vite does the minifying itself.
JavaScript inside styles
Old versions of Less let you write JavaScript right inside a value, in backticks: width: `16 * 2`px;. Since Less 3 this is disabled by default:
// styles/main.less
.sidebar {
width: `16 * 2`px;
}Compilation stops with the error Inline JavaScript is not enabled. You can turn it on with the --js flag or the javascriptEnabled: true option, but that is dangerous: any imported .less file could run arbitrary code on your computer or build server. Besides, the feature is deprecated and will be removed in Less 5.
Common mistake
When developers meet backticks in an old project, they turn on --js "just to make it build". It is better to replace the expression: Less operations are enough for arithmetic ((16px * 2)), and complex logic belongs in a plugin function like rem() above.