日常開發中總會有些不如意的地方。比如說,在 sass 中定義好了顏色變量,而在 template 卻不能直接使用,每次都要去找到對應的色彩值手動進行復制粘貼,真的是傷害不高,侮辱性極強!
那么,我們該如何解決這個問題呢?其實很簡單, 可以使用 CSS Modules 提供的 :export 關鍵字,示例如下
// styles/_variables.scss
$purple: #5344b6;
:export {
purple: $purple;
}
在 .vue 中使用
<template>
<div>
<van-icon :color="variables.purple"/>
</div>
</template>
<script>
import variables from '@/styles/_variables.scss'
export default {
data(){
return {
variables
}
}
}
</script>
為了方便管理,以及其它地方引用 _variables.scss
連同:export
一同被解析的問題,我們新建一個文件來管理提供變量給 js 的方法
// styles/_export.scss
@import './_variables.scss'
:export {
purple: $purple;
}
每次使用時都要定義個變量,是否還是有些不爽?別急,Vue 用戶的話,如下可以解決
<template>
<div>
<van-icon :color="$style.purple"/>
</div>
</template>
<style module lang="scss" src="@/styles/_export.scss"></style>
如果項目中使用了 typescript ,想要使用時有提示,則可定義對應的 ts 聲明文件
參考
- https://css-tricks.com/getting-javascript-to-talk-to-css-and-sass/
- https://github.com/css-modules/icss#export
- https://www.netguru.com/codestories/vue.js-scoped-styles-vs-css-modules
- https://vue-loader.vuejs.org/guide/css-modules.html#usage
- https://sergiocarracedo.es/2020/07/17/sharing-variables-between-scss-and-typescript/