You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Vite构建时CSS字体图标伪元素的Unicode转换

阻止Vite构建时将CSS字体图标转义序列转换为Unicode字符

问题场景

原CSS代码中的字体图标转义序列:

.icon-custom:before {
     content: "\e903";
}

执行vite build后被转换为:

.icon-custom:before{content:""}

需要阻止这种转换,已知Vite使用esbuild处理CSS压缩,通过设置charset=utf-8可解决该问题,以下是具体配置方案及复现细节。

解决方案

修改vite.config.js,在build选项中配置esbuild的CSS压缩参数,指定charset: "utf8":

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  build: {
    minify: 'esbuild',
    esbuild: {
      css: {
        charset: "utf8" // 保留CSS中的Unicode转义序列
      }
    }
  }
})

配置后执行vite build,CSS中的content: "\e903"会被保留,不会被转换为实际Unicode字符。

复现项目细节

项目结构

├── package.json
├── vite.config.js
├── index.html
└── src
    ├── App.vue
    └── main.js

package.json

{  
  "name": "vite-project",  
  "private": true,  
  "version": "0.0.0",  
  "type": "module",  
  "scripts": {    
    "dev": "vite",    
    "build": "vite build",    
    "preview": "vite preview"  
  },  
  "dependencies": {    
    "vue": "^3.4.37"  
  },  
  "devDependencies": {    
    "@vitejs/plugin-vue": "^5.1.2",    
    "vite": "^5.4.1"  
  }
}

vite.config.js(初始未配置版)

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
})

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/main.js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

src/App.vue

<template>Hello World<i class="icon-custom" /></template>

<style>
.icon-custom:before {
     content: "\e903";
}
</style>

复现步骤

  1. 执行npm install安装依赖
  2. 执行npm run build构建项目
  3. 查看dist文件夹中的CSS文件,可观察到转义序列被转换为Unicode字符

内容的提问来源于stack exchange,提问作者Hari Prasandh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 07:46:01