How to infer types from modular scss exports?
Asked Answered
M

1

4

I have found a way to import scss variables into ts and js using this article

Basically the approach is: Create a modular scss file containing your scss variables, or import them from the original files using @use.

// _globalVars.scss

$mobile-breakpoint: 900px;
// exporterFile.module.scss

@use './globalVars'

$new-variable: red;

:export {
  mobileBreakpoint: globals.$mobile-breakpoint;
  newVariable: $new-variable;
}

As you can see above, the required variables were exported using the :export{} syntax. These can then be imported into a JS or TS file.

import myScssVars from 'exporterFile.module.scss'

console.log(myScssVars); // { mobileBreakpoint: '900px', newVariable: 'red' }

Unfortunately these are imported as a readonly key value string pair. VSCode type annotation screenshot.

How do I infer the actual types for the variables set in scss?

Morsel answered 1/11, 2022 at 12:15 Comment(0)
S
3

I was able to achieve a similar behavior with the following lib: typed-scss-modules

So you need to do the following:

  • Install as a devDependency: yarn add -D typed-scss-modules

  • Go to you package.json and add a new script generate-scss-types: yarn typed-scss-modules src/yourPath/toMainScssFiles

  • Run the new script: yarn generate-scss-types

You should add a path to your main scss folder to prevent .d.ts files on very .scss file that you have on the project.

After doing it, you will have something like this:

/scss/
   --/ _color.variables.module.scss
   --/ _color.variables.module.scss.d.ts

Where _color.variables.module.scss had:

// primary
$primary: #2d64f1;
$primary-light: #7491ff;
$primary-dark: #003bbd;

/*
 * Color Map (used for color classes and direct usage in components)
 */
$colors: (
  'primary': $primary,
  'primaryLight': $primary-light,
  'primaryDark': $primary-dark,
);

:export {
  @each $name, $value in $colors {
    #{unquote($name)}: $value;
  }
}

And _color.variables.module.scss.d.ts will have:

export const primary: string
export const primaryDark: string
export const primaryLight: string

So then each time that you import your colors, you will have the IDE autocomplete and also the TS options like keyOf or typeOf

enter image description here

Side note:

This same approach will work for every other .scss file that you have, I just show you the colors, but the same will happen if you have "breakpoints" or "fonts"

Snowshoe answered 21/11, 2022 at 13:44 Comment(1)
Nice! It would be nice if this was possible without the extra library. Maybe there's some way to natively do what this library does.Morsel

© 2022 - 2024 — McMap. All rights reserved.