在Vue 3 + TypeScript 项目中,你可以通过以下步骤定义和使用全局SCSS变量:
- 安装
sass-loader和sass:
npm install --save-dev sass-loader sass- 在项目根目录下创建
styles文件夹,并在该文件夹中创建_variables.scss文件来定义你的全局SCSS变量:
// styles/_variables.scss
$primary-color: #3498db;
$secondary-color: #e74c3c;- 在
vue.config.js文件中配置sass-loader以使用dart-sass(node-sass已弃用):
// vue.config.js
module.exports = {
css: {
loaderOptions: {
sass: {
implementation: require('sass'),
additionalData: `@import "@/styles/_variables.scss";`
},
},
},
};- 在组件中使用这些变量:
<template>
<div :style="{ color: primaryColor }">
This text will be colored with the primary color.
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { primaryColor, secondaryColor } from '@/styles/_variables.scss';
export default defineComponent({
setup() {
return {
primaryColor,
secondaryColor
};
}
});
</script>
<style lang="scss">
.button {
background-color: $secondary-color;
}
</style>确保你的vue.config.js文件中已正确配置了sass-loader,并且在_variables.scss中定义的变量是可导出的(通常SCSS文件默认导出所有变量)。在组件的<style>标签中使用lang="scss"属性来指定你正在使用SCSS。在<script>中,你可以直接引入这些变量并在模板中使用。