Adding SASS to the dotnet React template

Out of the box, ASP.NET’s JavaScriptServices app generator has gotten pretty good. It gives you a decent starting point (if you like TypeScript) and even has a react-redux template. It doesn’t, however, come with any css extensions like SASS. There’s a not very user-friendly description in the docs of how to add it, but here’s the quick and dirty of how to add SASS to your project.

Disclaimer: This will not include hot module reloading for the scss files. ? This is very lame, but it’s discussed here that it’s better to build your css the same way in dev and prod (rather than using different loaders for the two environments), so until there’s a valid loader that can do both, this is the method they recommend.

  1. Install the required modules
    Using npm:

    npm install --save-dev node-sass sass-loader
  2. Update the webpack config(s)
    Find the rules block in your webpack config that are testing for /\.css$/ files. Modify that line to:

    { test: /\.s?css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader!sass-loader' : 'css-loader?minimize!sass-loader' }) }
  3. Rename your file(s)
    The default app has a file called “site.css” in the /css folder. Rename this to “site.scss”.
  4. Update your reference
    Wherever you are including your css into your app (by default, it’s in boot-client.tsx), change that reference to match your new file name:

    import './css/site.scss';

    Psst: DON’T change the file name in your webpack.config passed to the ExtractTextPlugin; that is specifying the name of the output file.

  5. Run your app, and load in a browser
    Run on the command line by using “dotnet run”, then open a browser to localhost:5000, or whichever port is specified. If your app is building in Production mode (it will say in the blurb when it boots up), then you can set the environment flag by running:

    SET ASPNETCORE_ENVIRONMENT=Development
  6. Add some SASS 
    At the top of your new .scss file, test it out by adding a variable, and then abuse that variable:

    $hideous-color: #f0f;
    
    body {
        background-color: $hideous-color;
    }
  7. Reload your app in the browser

You are now cookin’ with SASS. Terrible pun intended.