Search code examples
javascriptlessvite

How to add a loader (less-loader) to vite.js (vite.config.js)?


I started using Vite.js and I want to use less files in my project, I didn't find a clear solution to add a loader, especially less-loader beceause I am using Ant Design v4.

I used :

import react from '@vitejs/plugin-react';

export default {
  plugins: [react()],
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },
};

but it doesn't work, and I tried :

import react from '@vitejs/plugin-react';

export default {
  plugins: [
    {
      name: 'less',
      transform(code, id) {
        if (id.endsWith('.less')) {
          return require('less').renderSync({ data: code }).css;
        }
      },
    },
  ],
  css: {
    modules: {
      localsConvention: 'camelCaseOnly',
    },
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },
};

nothing works, I asked chatGPT but it gave me random solution and nones worked, any solution or article to learn how to configure loaders in vite.js ?


Solution

  • I am not sure what are the problems you are facing but I tried these steps and it's working fine for me.

    1. Installed less in the project

    2. I added support for math, relativeUrls along with javascriptEnabled in vite config

    css: {
        preprocessorOptions: {
          less: {
            math: "always",
            relativeUrls: true,
            javascriptEnabled: true
          },
        },
      }
    

    Here is code sandbox link of my basic setup of vite+reactjs+antd+less

    https://codesandbox.io/p/github/abhinavRai23/Vite-react-ant-design/main