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

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

安装

shell 复制代码
npm install vite-plugin-vue-style-bundler
// or
pnpm add vite-plugin-vue-style-bundler
// or 
yarn add vite-plugin-vue-style-bundler

使用方法

  • 第1步:启用插件
ts 复制代码
// 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步:编写组件
vue 复制代码
<template>
  <div class="hello">Hello, {{ msg }}</div>
</template>
<style bundle>
.hello {
  color: red;
}
</style>

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

diff 复制代码
<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之前执行。

推荐

相关推荐
涛涛ing2 分钟前
狂揽2.4万星标:一行命令,AI会自己找技能了
前端
Csvn3 分钟前
🚨 JSON.stringify 的 6 个隐藏坑:为什么你的数据序列化后"消失"了?
前端
aircrushin9 分钟前
Claude 5 之后,上下文工程该做减法了
前端·人工智能·后端
huabuyu11 分钟前
CLS 自动化归因及自愈:让系统自己定位根因、修复并验证
前端·javascript
C++、Java和Python的菜鸟11 分钟前
第13章 前端Web实战(Tlias案例)
前端·javascript·vue.js
用户69190268133912 分钟前
React 组件间通信全解析:从父子到跨级
前端·javascript
echoVic13 分钟前
同一个 bug,我在 WebGPU 渲染器里犯了两轮:一帧内多次写同一块 buffer
前端·webgl·图形学
胡萝卜术15 分钟前
数据主权与渲染防线:从受控组件到性能优化的完整图景
前端·javascript·面试
DFT计算杂谈16 分钟前
FeSe超薄膜在CaF2衬底上的电子结构DFT研究
java·服务器·前端
mONESY17 分钟前
React 组件通信进化史:从 Props 层层搬运到 Context 跨层级直达
javascript