自动捆绑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之前执行。

推荐

相关推荐
想要成为糕糕手几秒前
238. 除了自身以外数组的乘积 — 面试向深度解析
javascript·算法·面试
kisshyshy2 分钟前
前端存储、表单异步提交与 this 指向完全指南
前端·javascript·html
cidy_983 分钟前
Skills 技能库- JulyCode
前端
Kel7 分钟前
管道、IPC、Socket:你以为的三种技术,其实是同一件事
javascript·设计模式·node.js
Csvn7 分钟前
TypeScript 泛型约束的 3 层演进:从 `extends` 到条件类型到重载推导
前端
小四的小六8 分钟前
AI产品翻车实录:模型总结幻觉的三大类型与检测方案
前端·openai·ai编程
心中有国也有家9 分钟前
AtomGit Flutter 鸿蒙客户端: AnimatedScale 与 AnimatedContainer 联合实战
android·javascript·flutter·华为·harmonyos
狂师9 分钟前
端开发必装 Skill 清单:6 款 AI 技能,让你的开发效率原地起飞
前端·程序员·开源
3630458419 分钟前
KlineChartQuant Tooltip 高频交互 200FPS 性能优化完整复盘
前端·架构
嘉泰姆半导体官方13 分钟前
CXAR41337C 双通道数字音频功放 | 2×20W | EQ+DRC | I²S | MCLK-Less - 嘉泰姆电子
前端·javascript·数据库