安装依赖
pnpm add -D sass-embedded
配置全局变量
- 新建文件
src/styles/variables.scss
- 配置Vite 修改
vite.config.ts
variables.scss
$base-color: blue
vite.config.ts
// https://vite.dev/config/
export default defineConfig({plugins: [vue(),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url)) //相对路径别名配置,@代替src,用于打包时路径转换},},css: {preprocessorOptions: {// 引入公共scss变量scss: {// 引入 varibles.scss 这样就可以在全局中使用 varibles.scss中预定义的变量了// 给导入的路径最后加上 ;// as 后面是定义的环境变量// 如果写as * ,可以直接使用变量名,如:变量名// 如果不写as *, 默认文件名即:variables, 使用variables.变量名// 如果是as vars,则使用vars.变量名additionalData: '@use "@/assets/styles/variables" as *;',},},},
})
引入全局样式
- 创建文件
src/assets/styles/reset.scss
,src/assets/styles/index.scss
- 引入全局样式
main.ts
reset.scss
// 重置样式 https://www.npmjs.com/package/reset.css?activeTab=code
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {margin: 0;padding: 0;border: 0;font-size: 100%;font: inherit;vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {display: block;
}
body {line-height: 1;
}
ol, ul {list-style: none;
}
blockquote, q {quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {content: '';content: none;
}
table {border-collapse: collapse;border-spacing: 0;
}
index.scss
// 引入重置样式
@use 'reset';
main.ts
...
const app = createApp(App)
...
// 引入全局样式
import '@/assets/styles/index.scss'app.mount('#app')
使用测试
<template><div class="home"><h2>Home</h2> </div>
</template><script setup lang="ts">
</script><style scoped lang="scss">
.home {h2 {color: $base-color;}
}
</style>