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

推荐

相关推荐
狗头大军之江苏分军17 分钟前
《潮水漫过十七岁》 加一个蛋,顺便说一下我解放了
前端·后端
Captaincc32 分钟前
掘金AI用量迎来重大更新!全新AI用量
前端·后端
天若有情6731 小时前
开源|纯前端·条码&二维码在线生成器,支持拖拽缩放、复制生成码图片
前端·javascript·开源·html·二维码·条形码
map_vis_3d3 小时前
控制百度地图视野:setCenter、setZoom、panTo、flyTo 和 setViewport
前端·javascript·地图·百度地图
map_vis_3d3 小时前
百度地图 3D 视角:倾斜 tilt 与旋转 heading
前端·webgl·地图·百度地图·三维
Hilaku4 小时前
前端到底要不要写单元测试?
前端·javascript·程序员
ikoala4 小时前
每个独立开发者上线前,务必用这个skill做一次安全漏洞自查
前端·javascript·后端
anyup5 小时前
uni-app x 的 Signature 签名板与练字格,一个组件多端支持 App/鸿蒙/H5/小程序
前端·vue.js·uni-app
艾莉丝努力练剑5 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
oil欧哟6 小时前
为什么我们不建议盲目构建多 Agent 系统
前端·后端