Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Tooling and Build

Sass with Vite, webpack, PostCSS and Frameworks

Wire Sass into modern build tools: Vite, webpack sass-loader, Laravel, Next.js and Angular, plus PostCSS autoprefixer and cssnano, additionalData, package imports and CSS Modules.

In a real project you rarely type sass by hand. A bundler (Vite, webpack, Parcel) or a framework (Laravel, Next.js, Angular) runs Sass for you whenever you import a .scss file, adds a dev server with instant reload, and hands the CSS to the next stage of the pipeline: prefixing, minifying, hashing file names. This lesson shows how the pieces connect and the Sass-specific options you will actually touch.

The configuration snippets are read-only because a bundler cannot run inside this page; the compiler call they make is the same compileString you used in the JavaScript API, and the miniature below simulates what the most useful option does.

The pipeline

flowchart LR
  S["main.scss"] --> SA["Sass compiler"]
  SA --> P["PostCSS: autoprefixer, nesting, preset-env"]
  P --> M["Minify: cssnano / Lightning CSS"]
  M --> H["Hashed file: app.4f2a.css"]
  SA -. "source map" .-> H

Sass is one stage. The rest of the pipeline works on plain CSS.

Vite

Vite supports Sass with no configuration after you install the compiler:

Terminal
npm install -D sass-embedded

Then import the stylesheet from JavaScript (or reference it in HTML):

JavaScript
// main.js
import "./styles/main.scss";

In development Vite serves the compiled CSS with hot module replacement, so edits show up without a reload. In vite build it compiles, processes with PostCSS, minifies and writes a hashed file.

Options live under css.preprocessorOptions.scss:

JavaScript
// vite.config.js
import { defineConfig } from "vite";

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        api: "modern-compiler",                 // use the modern API with sass-embedded
        additionalData: `@use "@/styles/tokens" as *;\n`,
        loadPaths: ["src/styles"],
        quietDeps: true,
      },
    },
  },
});

additionalData is prepended to every Sass file. That lets all partials use tokens without writing @use each time. It is convenient but implicit, so a reader of a partial cannot see where $brand comes from. Prefer explicit @use in each file for libraries and large teams; use additionalData for small apps.

What additionalData does

Delete the $brand line from the additionalData and read the error: Sass says the variable is undefined, because the second file stands alone otherwise. (The simulation is a one-file concatenation; real bundlers do this per file.) Note that @use rules must come first, which is why additionalData begins with @use.

webpack

webpack needs loaders in a chain, read right to left (or bottom to top):

JavaScript
// webpack.config.js
import MiniCssExtractPlugin from "mini-css-extract-plugin";

export default {
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          MiniCssExtractPlugin.loader,   // 4. write a .css file (use style-loader in dev to inject <style>)
          "css-loader",                  // 3. resolve url() and @import in CSS
          "postcss-loader",              // 2. autoprefixer etc.
          {
            loader: "sass-loader",       // 1. compile Sass
            options: {
              api: "modern-compiler",
              sassOptions: { loadPaths: ["node_modules"], quietDeps: true },
              additionalData: `@use "tokens" as *;`,
            },
          },
        ],
      },
    ],
  },
  plugins: [new MiniCssExtractPlugin()],
};

sass-loader calls the compiler with source maps if devtool is set, and passes loadPaths. Older guides use the ~ prefix (@import "~bootstrap/scss/bootstrap") to say "look in node_modules". Modern sass-loader and the pkg: importer make that unnecessary: @use "bootstrap/scss/bootstrap" works with loadPaths: ["node_modules"].

Laravel (Vite)

Laravel projects use Vite. Install the compiler, then point the plugin at a Sass entry file:

Terminal
npm install -D sass-embedded
JavaScript
// vite.config.js
import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";

export default defineConfig({
  plugins: [
    laravel({ input: ["resources/sass/app.scss", "resources/js/app.js"], refresh: true }),
  ],
});
BLADE
@vite(["resources/sass/app.scss", "resources/js/app.js"])

Older Laravel versions used Laravel Mix: mix.sass("resources/sass/app.scss", "public/css").

Next.js, Angular and others

  • Next.js: npm install sass, import .scss files in components, or use CSS Modules with the .module.scss suffix (class names are made unique per file). Shared helpers: sassOptions: { includePaths: [...], additionalData: "..." } in next.config.js.
  • Angular: create the project with ng new --style=scss; set "stylePreprocessorOptions": { "includePaths": ["src/styles"] } in angular.json for shorter imports; component styles are encapsulated per component.
  • Vue and Svelte: add lang="scss" to a <style> block (<style lang="scss" scoped>), plus the sass package.
  • Parcel: works out of the box once sass is installed.
  • Eleventy, Astro, Jekyll: the static-site generators either compile Sass for you (Jekyll, Astro with sass installed) or you run the CLI as a build step.

PostCSS and the post-processing stage

Sass compiles your language to CSS, but CSS itself still needs care for browser compatibility and size. PostCSS is a pipeline of small plugins that transform the CSS output:

JavaScript
// postcss.config.js
export default {
  plugins: {
    "postcss-preset-env": { stage: 2 },   // modern CSS syntax -> what your browsers support
    autoprefixer: {},                      // adds vendor prefixes using your browserslist
    cssnano: { preset: "default" },        // minify in production
  },
};
JSON
// package.json
{ "browserslist": ["defaults", "not dead", ">0.5%"] }

Autoprefixer reads the browserslist list, so you write user-select: none and it adds the prefixed version only if your targets need it. Do not write vendor prefixes in Sass by hand. (Lightning CSS is a faster all-in-one alternative that Vite can use with css.transformer: "lightningcss".)

Order matters: Sass first, PostCSS after. PostCSS plugins understand CSS, not Sass syntax, so they must see the compiled output.

Removing unused CSS

Utility generators and frameworks produce far more CSS than a page uses. Tools such as PurgeCSS scan your HTML, templates and JavaScript for class names and delete unmatched rules. Tell the tool about classes added at runtime (a safelist) or it will remove them. See performance and output size.

Common problems

  • "Can't find stylesheet to import" for a package: add node_modules to load paths or use pkg: URLs.
  • Slow builds: switch to sass-embedded, enable the modern API, and keep @use instead of @import (modules are evaluated once).
  • Flood of deprecation warnings from a dependency: quietDeps: true.
  • Styles not updating in watch mode inside Docker or WSL: enable polling in the bundler's watcher.
  • Different results in dev and build: check that both use the same PostCSS config and Sass version.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must you install for Vite to compile .scss files?

    Vite supports Sass without a plugin; you only install the compiler as a dependency.
  2. 2. What does additionalData do?

    It injects shared Sass (often @use of tokens) at the top of each file.
  3. 3. In which order should Sass and PostCSS run?

    PostCSS plugins work on CSS, so they need Sass's compiled output.
  4. 4. Which file name triggers CSS Modules for Sass in Next.js?

    The .module.scss suffix makes class names locally scoped.
  5. 5. What does Autoprefixer rely on to decide which prefixes to add?

    The target browsers listed in browserslist determine the prefixes.

Summary

  • Bundlers call the same Sass compiler for you; install sass or sass-embedded and import a .scss file.
  • Vite needs no config; use css.preprocessorOptions.scss for additionalData, loadPaths and quietDeps.
  • webpack chains sass-loader, postcss-loader, css-loader and an extraction plugin; Laravel, Next.js, Angular, Vue and Parcel have built-in paths.
  • PostCSS (autoprefixer, preset-env, cssnano) post-processes the compiled CSS; Sass runs first.
  • Remove unused CSS with a purge tool and safelist runtime classes.

Next: Debugging Sass