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

推荐

相关推荐
默恋~微凉5 分钟前
shell(八)——WEB与Nginx
开发语言·前端·php
要加油哦~14 分钟前
nrm | npm 的镜像管理工具
前端·npm·node.js·nrm
想不明白的过度思考者15 分钟前
基于 Spring Boot 的 Web 三大核心交互案例精讲
前端·spring boot·后端·交互·javaee
孟祥_成都15 分钟前
不易懂你打我!写给前端和小白的 大模型(ChatGPT) 工作基本原理!
前端·人工智能
恋猫de小郭20 分钟前
回顾 Flutter Flight Plans ,关于 Flutter 的现状和官方热门问题解答
android·前端·flutter
●VON21 分钟前
从零开始:用 Electron 构建你的第一个桌面应用
前端·javascript·electron
艾小码22 分钟前
从源码到npm:手把手带你发布Vue 3组件库
前端·vue.js·npm
张风捷特烈27 分钟前
FlutterUnit3.4.1 | 来场三方库的收录狂欢吧~
android·前端·flutter
t***L2661 小时前
JavaScript在机器学习中的库
开发语言·javascript·机器学习
乔冠宇1 小时前
CSS3中的新增属性总结
前端·javascript·css3