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.
.
How do I infer the actual types for the variables set in scss?
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.tsfiles on very.scssfile 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

Side note:
This same approach will work for every other
.scssfile that you have, I just show you the colors, but the same will happen if you have "breakpoints" or "fonts"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With