Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Less with Vite

Vite is a popular tool for front-end projects: it runs a development server and builds the site for publishing. Vite compiles Less by itself — you only install the less package and import a .less file. No separate watch script is needed.

Creating a project

Create a project from the plain JavaScript template and install the compiler:

npm create vite@latest site -- --template vanilla
cd site
npm install
npm install --save-dev less

Vite does not include Less; it finds the less package in the project's node_modules.

Where the styles live

In a Vite project the code lives in src/. Put the styles in src/styles/:

site/
├── index.html
├── src/
│   ├── main.js
│   └── styles/
│       └── main.less
└── package.json

Everything you see in this course under styles/ goes into src/styles/ in a Vite project. Create src/styles/main.less:

// src/styles/main.less
@primary: #2563eb;
 
h1 {
  color: @primary;
}

Importing the styles

Vite adds styles to the page when JavaScript imports them. Open src/main.js, remove the template code and import the file:

// src/main.js
import './styles/main.less';
 
document.querySelector('#app').innerHTML = '<h1>My site</h1>';

Start the development server:

npm run dev

Open http://localhost:5173: the heading is blue. Change @primary and save — the page updates instantly without a reload.

Building

For publishing, build the project:

npm run build

Vite compiles the Less, minifies the CSS and puts it into dist/assets/ with a hash in the file name, for example index-B7f3kQ2a.css. The dist/ folder is what you upload to the server.

Less options in Vite

Compiler options go into vite.config.js. For example, this turns on the old division behaviour:

// vite.config.js
import { defineConfig } from 'vite';
 
export default defineConfig({
  css: {
    preprocessorOptions: {
      less: {
        math: 'always',
      },
    },
  },
});

The less object takes the same options as lessc, written as properties. Without this file Vite uses the defaults, which is enough for this course.

Common mistake

If you import a .less file without installing the less package, the dev server shows an error saying the preprocessor dependency is not found. Run npm install --save-dev less and restart npm run dev.

Thanks for reading!

Donate to the site — we work hard for you.