Vue2 + Vite: css preprocessor additionalData SFC styles

607 views Asked by At

So I'm working with vue 2.7.14. Moving from webpack to vite. All my scss styles in every component (SFC) are not loading. Actually, the style is loaded in the head tag, but it is adding some url params to the url and not loading the styles to the component (see 'html output')

If I put my scss files to load with vite.config.js inside the preprocesorOption, it will load and apply styles, but I want my components styles to be load in every component.

Reproduction of the case: https://stackblitz.com/edit/vitejs-vite-n72kb6

vite.config.js

css: {
      preprocessorOptions: {
        scss: {
          // THIS WAY ALL THE STYLES IN SFC ARE NOT LOADING
          // UNLESS I ADD HERE STYLES ONE BY ONE (see last one commented)
          additionalData: () => {
          let prepends = '';
          prepends += `$app: ${app};`;
          prepends += `@import "@/style.scss";`;
          prepends += `@import "@/assets/vite/scss/colors.scss";`;
          // prepends += `@import "@/components/searchbar/scss/searchbar.scss";`;
          return prepends;
          }
        },
      },
    },

saerchbar.vue

<template src="./searchbar.html"></template>
<!--THIS IS NOT LOADING UNLESS I ADD IT TO THE vite.config.js-->
<style lang="scss" src="./searchbar.scss"></style> 

<script>...</script>
1

There are 1 answers

0
Julieta On

The problem here is the way Im using the additionalData function.

It seems that when using "additionalData" as a function, will completely take control and as the content is passed as the first argument, we have to manually return it:

additionalData: (content) => {
  let prepends = '';
  prepends += `$app: ${app};`;
  prepends += `@import "@/style.scss";`;
  prepends += `@import "@/assets/vite/scss/colors.scss";`;
  prepends += content;

  return prepends;
}

or use the "additionalData" as a sass string:

additionalData: `
  $app: ${app};
  @import "@/style.scss";
  @import "@/assets/vite/scss/colors.scss";
`,

I used this last way as string using template literals and everything works fine now.

IMPORTANT: Avoid adding any css in additionalData as it is going to get duplicated for every component that has scss. Use it for global, variables, mixins...