uniapp在:class中的样式使用tailwindcss样式后,在上传小程序中会报错 —— unexpected character \
原因是WXML将’转译成了",只需要打包时将"转回’即可解决问题
话不多说上干货,将下面代码写入vite.config.js中
import fs from 'fs'
import path from 'path'

// 自定义 WXML 替换插件
const vitePluginWxmlReplace = () => {
  return {
    name: 'vite-plugin-wxml-replace',
    // 监听打包完成钩子(writeBundle:文件已写入输出目录)
    async writeBundle(options, bundle) {
      // 获取打包输出根目录
      const outputPath = options.dir || 'dist'
      // 仅处理微信小程序平台
      if (!outputPath.includes('mp-weixin')) return

      console.log('🔧 开始替换 WXML 文件中的反斜杠...')
      // 递归遍历并替换文件
      replaceFilesInDir(outputPath)
      console.log('✅ WXML 反斜杠替换完成:所有 \\ 已替换为 \'')
    }
  }

  // 递归遍历目录,处理所有 .wxml 文件
  function replaceFilesInDir(dir) {
    const files = fs.readdirSync(dir)
    files.forEach(file => {
      const filePath = path.join(dir, file)
      const stat = fs.statSync(filePath)

      if (stat.isDirectory()) {
        replaceFilesInDir(filePath) // 递归处理子目录
      } else if (filePath.endsWith('.wxml')) {
        // 仅处理 WXML 文件
        let content = fs.readFileSync(filePath, 'utf-8')
         content = content.replace(/\\"/g, "'") // 核心替换逻辑
        fs.writeFileSync(filePath, content, 'utf-8')
      }
    })
  }
}

最后注册使用即可

export default defineConfig({
  plugins: [
    uni(),
    vitePluginWxmlReplace() // 注册自定义插件
  ]
})
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐