Detailed explanation of how to use css variable in JS
- 2021-11-13 06:45:29
- OfStack
How to use css variables in JS
Use the: export keyword to export an js object in the less/scss file.
$menuText:#bfcbd9;
$menuActiveText:#409EFF;
$subMenuActiveText:#f4f4f5;
// $menuBg:#304156;
$menuBg:#304156;
$menuHover:#263445;
$subMenuBg:#1f2d3d;
$subMenuHover:#001528;
$backWhite:#ffffff;
$sideBarWidth: 210px;
:export {
menuText: $menuText;
menuActiveText: $menuActiveText;
subMenuActiveText: $subMenuActiveText;
menuBg: $menuBg;
menuHover: $menuHover;
subMenuBg: $subMenuBg;
subMenuHover: $subMenuHover;
sideBarWidth: $sideBarWidth;
backWhite: $backWhite;
}
Reference in the required js file or module.
import style from 'index.scss'
console.log(style.menuText)
vue file
import style from 'index.scss'
export default {
computed:{
style(){
return style
}
}
}
Implementation principle
Webpack: Enable CSS Modules in the project in conjunction with css-loader.
CSS Modules: CSS Modules solves both style import and export problems internally through ICSS. Corresponding to two new pseudo classes: import and export respectively.
Attachment: javascript keyword of export
The Javascript keyword (Reserved Words) refers to those words that have a specific meaning in the Javascript language and become part 1 of the Javascript syntax. The Javascript keyword cannot be used as a variable name or function name. Using the Javascript keyword as a variable or function name causes Javascript to have a compilation error during loading.
Javascript keyword list:
break, delete, function, return, typeof
case, do, if, switch, var
catch, else, in, this, void
continue, false, instanceof, throw, while
debugger, finally, new, true, with
default, for, null, try
Javascript Future Keyword List:
abstract, double, goto, native, static
boolean, enum, implements, package, super
byte, export, import, private, synchronized
char, extends, int, protected, throws
class, final, interface, public, transient
const, float, long, short, volatile