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

vite-plugin-vue-style-bundler

开发Vue组件时,编译产物由js和css组成,导入该组件时需要同时导入js和css。
vite-plugin-vue-style-bundler可以实现 自动提取Vue组件中的css样式一起打包到js源代码中,然后在运行时将style自动插入到head的vite插件。

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

推荐

相关推荐
vx_Biye_Design5 小时前
springboot一站式旅游管理平台81037-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·课程设计·express·旅游
vx_Biye_Design5 小时前
springboot宠物寄养服务预约与监管系统82684-计算机课程设计、毕业设计
java·vue.js·spring boot·elasticsearch·课程设计·express·宠物
vx_Biye_Design5 小时前
springboot小学生英语学习APP62773-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·学习·课程设计
vx_Biye_Design6 小时前
expressDeepSeek社团咨询助手的学生社团管理系统60746-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·课程设计·express
传人6 小时前
悬停旋转放大和位移效果如何写
前端·javascript·css
vx_Biye_Design6 小时前
springboot宠物领养与救助平台64334-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·mysql·课程设计·宠物
vx_Biye_Design6 小时前
django就业信息推荐系统61953-计算机课程设计、毕业设计
java·vue.js·spring boot·python·架构·django·课程设计
羲云6 小时前
给 Vue 页面加个 Markdown 编辑器:ME.js 的接入、图片粘贴与音视频
javascript·vue.js
zhangzeyuaaa7 小时前
Ruby 方法参数完全指南:默认值、可变参数与关键字参数
前端·python·ruby
粥里有勺糖7 小时前
视野修炼-技术周刊第135期 | 鼠标跟随宠物
前端·github·aigc