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

推荐

相关推荐
你挚爱的强哥17 分钟前
【sgCreateCallAPIFunctionParam】自定义小工具:敏捷开发→调用接口方法参数生成工具
前端·javascript·vue.js
喝旺仔la23 分钟前
Element 表格相关操作
javascript·vue.js·elementui
繁依Fanyi26 分钟前
使用 Spring Boot + Redis + Vue 实现动态路由加载页面
开发语言·vue.js·pytorch·spring boot·redis·python·算法
米老鼠的摩托车日记26 分钟前
【vue element-ui】关于删除按钮的提示框,可一键复制
前端·javascript·vue.js
forwardMyLife26 分钟前
element-plus的菜单组件el-menu
javascript·vue.js·elementui
猿饵块1 小时前
cmake--get_filename_component
java·前端·c++
好多吃的啊1 小时前
背景图鼠标放上去切换图片过渡效果
开发语言·javascript·ecmascript
大表哥61 小时前
在react中 使用redux
前端·react.js·前端框架
Passion不晚1 小时前
打造民国风格炫酷个人网页:用HTML和CSS3传递民国风韵
javascript·html·css3
十月ooOO1 小时前
【解决】chrome 谷歌浏览器,鼠标点击任何区域都是 Input 输入框的状态,能看到输入的光标
前端·chrome·计算机外设