自动捆绑Vue组件CSS样式-CSS-IN-JS

本文介绍了vite-plugin-vue-style-bundler插件如何实现在Vue组件中自动合并CSS到JS,简化导入过程。通过配置和使用方法,开发者可以便捷地在开发组件库时管理样式导入。
摘要由CSDN通过智能技术生成

vite-plugin-vue-style-bundler

开发Vue组件时,编译产物由jscss组成,导入该组件时需要同时导入jscss
vite-plugin-vue-style-bundler可以实现 自动提取Vue组件中的css样式一起打包到js源代码中,然后在运行时将style自动插入到headvite插件。
这样,经过vite-plugin-vue-style-bundler处理后,导入组件时就只需要导入js就可以了,这在开发组件库时特殊方便。

访问Github

安装

npm install vite-plugin-vue-style-bundler
// or
pnpm add vite-plugin-vue-style-bundler
// or 
yarn add vite-plugin-vue-style-bundler

使用方法

  • 第1步:启用插件
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue' 
import StyleBundler from "vite-plugin-vue-style-bundler"

export default defineConfig({
  plugins: [    
    vue(),
    StyleBundler({    
        // lessOptions:{},  如果需要使用less,可以配置lessOptions
        // sassOptions:{}   如果需要使用sass,可以配置sassOptions
    }) 
  ],
})


  • 第2步:编写组件
<template>
  <div class="hello">Hello, {{ msg }}</div>
</template>
<style bundle>
.hello {
  color: red;
}
</style>

当在组件的style标签上添加bundle属性后,vite-plugin-vue-style-bundler插件会对该组件源码进行处理。


<template>
  <div class="hello">Hello, {{ msg }}</div>
</template>
<script setup>
+   const $insertStylesheet = (id,css)=>{
+        let style = document.getElementById('ho79thw')
+        if(!style){
+            style = document.createElement("style")
+            style.id = 'ho79thw'
+            document.head.appendChild(style)            
+            style.innerHTML = css
+        }
+    }
+    $insertStylesheet(`
+      .hello {
+        color: red;
+      }
+    `)
</script>
- <style bundle>
- .hello {
-   color: red;
- }
- </style>

说明

  • 插件会在当前vue文件的<script setup>中自动注入代码。
  • 样式会被注入到headstyle标签中,style.id默认是根据当前vue文件的路径生成的。也可以通过<style bundle='styleId'>来指定style.id
  • 如果需要使用less或者sass,可以在插件配置中添加lessOptions或者sassOptions
  • 插件的enforce="pre",这意味插件总是@vitejs/plugin-vue之前执行。

推荐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值