美文网首页
Vite从入门到精通(三)Vite中CSS解决方案

Vite从入门到精通(三)Vite中CSS解决方案

作者: 程序员三千_ | 来源:发表于2023-04-06 18:06 被阅读0次

    目的:在Vite构建的项目中,如何使用普通CSS和CSS预处理器

    1、普通CSS的使用

    我们在项目的src目录下新建一个styles文件夹,在styles文件夹里新建两个css文件


    • index.css
    @import url(@/styles/other.css);
    .msg {
        color: red;
    }
    
    • other.css
    div {
        background-color: blueviolet;
    }
    

    然后在index.css中导入other.css,最后在页面中使用。

    <script setup>
    import "@/styles/index.css"
    </script>
    
    <template>
      <div class="msg">{{ msg }}</div>
    </template>
    
    • 运行看下效果:div的背景颜色和文字的颜色都是我们分别在index.css和other.css里设置的颜色

    这里我们要注意,我们在index.css中导入other.css的时候,我们直接使用了@import url(@/styles/other.css),而不是使用@import url(/src/styles/other.css),因为我们在配置文件里设置了src别名alias

    这个别名alias在日常项目开发中使用的频率是非常高的,但在Vite中设置别名alias和在webpack中设置别名alias又有点不一样,所以我们这里提出来讲一下。

    2、CSS 预处理器的使用

    CSS 预处理器,Vite 提供了对 .scss, .sass, .less, .styl 和 .stylus 文件的内置支持。没有必要像webpack项目一样,为它们做特殊的配置,在Vite项目里只要安装相应的依赖就可以了,我们这里拿sass举个例子

    我们先需要安装sass

    npm install --save-dev sass
    

    然后在项目的styles文件夹里新建两个scss文件


    image.png
    • sass1.css
    @import url(@/styles/sass2.scss);
    .test1 {
        color: white;
    }
    
    $font-size-normal: 32px;
    
    • sass2.css
    .test1 {
        background-color: chocolate;
    }
    

    然后在sass1.css中导入sass2.css,最后在页面中使用.

    <template>
      <p class="test1">测试sass</p>
    
    </template>
    
    <style scoped lang="scss">
    @import "@/styles/sass1.scss";
    
    .test1 {
      font-size: $font-size-normal;
    }
    </style>
    

    总结

    当然,如果你的项目包含有效的 PostCSS 配置 (任何受 postcss-load-config 支持的格式,例如 postcss.config.js),它将会自动应用于所有已导入的 CSS。
    由于 Vite 的目标仅为现代浏览器,因此Vite的作者也更推荐使用原生 CSS 变量和实现 CSSWG 草案的 PostCSS 插件(例如 postcss-nesting)来编写简单的、符合未来标准的 CSS。

    相关文章

      网友评论

          本文标题:Vite从入门到精通(三)Vite中CSS解决方案

          本文链接:https://www.haomeiwen.com/subject/gujuddtx.html