I use Bootstrap with SASS in my React (Next.js) project. I would now like to use the SASS variables of Bootstrap in the SASS modules (scoped) of the components.
/styles/style.scss
@import "~bootstrap/scss/functions";
@import "~bootstrap/scss/variables";
@import "~bootstrap/scss/mixins";
@import "~bootstrap/scss/maps";
@import "~bootstrap/scss/utilities";
@import "~bootstrap/scss/utilities/api";
@import "~bootstrap/scss/containers";
@import "~bootstrap/scss/grid";
@import "~bootstrap/scss/root";
@import "~bootstrap/scss/reboot";
/pages/_app.tsx
import '../styles/style.scss'
/components/text/style.module.scss
.text {
font-size: $font-size-lg;
}
Of course, I now get an error because $font-size-lg
was not defined.
How do I provide the bootstrap variables in the module files so I can use them?
CodePudding user response:
I have checked the "How to Use Sass with CSS Modules in Next.js" guide at freecodeCamp and it seems that you should import the bootstrap variables
directly in your scss
module.
Will it not work, if you import your /styles/style.scss
in the /components/text/style.module.scss
with the following import command?
@import "../../styles/style.scss"
Unfortunately, I cannot check it myself.
CodePudding user response:
What is the problem ?
You are importing the Bootstrap SASS variables file
in your global style.scss
file. However, the SASS modules
(scoped) of your React components are not aware of the variables
defined in the global file
.
Solution
One way to make the variables available in your SASS modules is to define them again in the module files, this way you'll have to import the variables file in every SASS file.
To avoid importing variables file in every SASS file is by defining them globally in a way that they are shared among all the SASS files. You can do this by using the CSS :export
directive.
For example, in your style.scss
file, you can define the variables using the :export
directive:
@import "~bootstrap/scss/variables";
:export {
font-size-lg: $font-size-lg;
// other variables
}
Then in your SASS modules (scoped) of your React components, you can import these variables by using the :import
directive:
:import {
font-size-lg
} from '../styles/style.scss';
.text {
font-size: font-size-lg;
}
Extra
You can also use a library like sass-module-dts-generator
that will generate a typeScript file with all the exported variables, this way you'll be able to use them in your JavaScript code.