warning: "@charset" must be the first rule in the file }@charset "UTF-8";

317 阅读1分钟

环境: vue3.2 + vite + tailwindcss 报错:

image.png

根据gitlab中vite/issess:github.com/vitejs/vite… 获取到以下思路(也有很多类似文档,比如:juejin.cn/post/708930… ):

css: {
      preprocessorOptions: {
        scss: {
          charset: false
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ],
      },
    },

警告问题解决了,但是带来了更大的问题,部分样式丢失了,页面展示混乱 正常情况下在vite.config.js中配置以上代码就可以解决问题,但是由于项目中用到了tailwindcss,所以在postcss中需要require tailwindcss和autoprefixer。如下:

css: {
      preprocessorOptions: {
        scss: {
          charset: false
        }
      },
      postcss: {
        plugins: [
          require('tailwindcss'), // 关键
          require('autoprefixer'), // 关键
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ],
      },
    },