Working with Sass & Create React App v2

Photo by Jacob Mejicanos on Unsplash

Create React App is one of the most beloved tools of the frontend community (approaching ~2M as of writing this). When I heard Sass and CSS Modules were being supported right of the box, I was pretty excited! CRA could potentially be used as a production app without ejecting. Gone were the days of configuring Webpack!

The Let Down…

Like most developers, I whipped out my computer and npm installed the updated CRA, and installed my favorite React Button. I added basic markup to App.js and npm start‘ed. I ran into the error…

File to import not found or unreadable: @material/react-button/index.
in /Desktop/my-app/src/App.scss (line 1, column 1)

btw my App.scss looked like this:

@import '@material/react-button/index'; // pretty simple, right??

Long Story Short

Basically the issue is the MDC Web and React libraries don’t have a ~ in front of their Sass import names (~@material/react-button/index). If that tilda existed, node-sass knows that the file path is found in the node_modules directory. But there are other flavors of Sass (ie. ruby-sass), which do not use the ~ convention — so sucks for us JS people.

Hours of Googling and reading and responding on forums, I finally found a solution (credit goes to @robcaldecott). Basically node-sass has an environment variable hook, when set is used to resolve imports. And thus was born my SASS_PATH entry in my .bash_profile (for the MacOSX users out there). It looks like this:

// relative path to your node_modules from your app root directory
export SASS_PATH=./node_modules

Source the .bash_profile, and voila all your npm imports with Sass now work! Again all was right in the world.

For those of you not on Mac, or need more instruction on environment variables, check out this doc. Just wanted to share this easy and amazing one-liner to save you headache and get you using CRA as intended.

Happy Coding!