Search code examples
node.jssassnestjsnode-sass

Compile SCSS to CSS in Nest.js


How can I tell to Nest.JS to compile my SCSS files from assets into CSS format?

I have wrote this into nest-cli.json:

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      {
        "include": "./assets/**.scss",
        "outDir": "./assets/",
        "watchAssets": true
      }
    ]
  }
}

But SCSS files are being copied without a conversion and I have no idea how to achive this.


Solution

  • Looks like Nest itself does not have the required tools, but you can compile SCSS to CSS with your script.

    To do this you need to install node-sass and concurrently to run it with Nest together:

    npm i --save-dev node-sass concurrently
    

    Then go into package.json and modify scripts section: add tasks for SASS compilation and inject them into main build tasks:

    scripts: {
        // ...
    
        // Add:
        "css-once": "node_modules/node-sass/bin/node-sass src/css/style.scss assets/style.css",
        "css-watch": "npm run css-once && node_modules/node-sass/bin/node-sass src/css/style.scss assets/style.css --watch",
    
        // Modify:
        "start": "npm run css-watch && nest start",
        "start:dev": "concurrently --kill-others \"npm run css-watch\" \"nest start --watch\"",
        "start:debug": "concurrently --kill-others \"npm run css-watch\" \"nest start --debug --watch\"",
        "start:prod": "npm run css-once && node dist/main",
    
    }
    

    Note, that there are two different tasks for initial CSS compilation and for watching changes because node-sass in watch mode won't compile SCSS initially.