Use Sass Variables In Typescript & Javascript

Having one true source of data is one of the first golden rules in software development. When creating components in JavaScript, you may want to add matching style properties and classes from your scss files. In an ideal world, you want to be able to make changes to these styles in one place and let your code update the rest.

I'm assuming you already have NPM setup with TypeScript and Sass. If you don't already have webpack added, install it with npm install --save-dev webpack webpack-cli.

Next install the loaders webpack should use for css: npm install --save-dev style-loader css-loader sass-loader.

Now in your webpack file you can add your loaders to handle any scss file.

module.exports = {
    module: {
        rules: [
                test: /\.scss$/,
                loaders: ["style-loader", "css-loader", "sass-loader"]

Once you've done this, you add a special :export to your Sass files so that TypeScript will recognise them.

$textColor: #333;
$primaryColor: #0F0;
$secondaryColor: #F0F;

// Here's the export you add.
:export {
  textColor: $textColor;
  primaryColor: $primaryColor;
  secondaryColor: $secondaryColor;

This is all that's needed for JavaScript. With JavaScript you can now use import styles from 'yourFileName.scss';.

For TypeScript you need to add a type definition. One option is to replace the "css-loader" in webpack with typings-for-css-modules-loader. That will generate type definitions for you. I prefer more control over my definitions though. I manually create my own yourFileName.scss.d.ts file. For the above example it would look like the following:

export interface I_globalScss {
  primaryColor: string;
  accentColor: string;
  textColor: string;

export const styles: I_globalScss;

export default styles;

Now using TypeScript I can use import styles from 'yourFileName.scss';. What's even better is when I type the period after styles in my TypeScript file, VS Code will give me hints on what properties I can use.

Matt Ferderer

Full Stack Software Developer focused on JavaScript and C#. Love to share & help others make amazing things. Have a project you need help on? Let's talk!