CSS自适应分辨率 postcss-pxtorem(适用于 Vite)
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import styleImport from 'vite-plugin-style-import';
// 自动导入组件库样式
const path = require('path');
const resolve = (dir) => path.join(__dirname, dir);
export default defineConfig({
plugins: [
vue(),
styleImport({
libs: [
{
libraryName: 'element-plus',
resolveStyle: (name) => {
return `element-plus/theme-chalk/${name}.css`;
},
resolveComponent: (name) => {
return `element-plus/lib/${name}`;
},
},
],
}),
],
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/element/index.scss" as *;`,
},
},
},
// 配置postcss-pxtorem
esbuild: {
jsxFactory: 'h',
jsxFragment: 'Fragment',
plugins: [
{
name: 'autoprefixer',
setup(build) {
const postcss = require('postcss');
const pxtorem = require('postcss-pxtorem');
build.onLoad({ filter: /\.scss$/ }, async (args) => {
const contents = await fs.readFile(args.path, 'utf8');
const result = await postcss([
pxtorem({
rootValue: 16,
propList: ['*'],
}),
]).process(contents, { from: undefined });
return { contents: result.css, loader: 'css' };
});
},
},
],
},
});
这个代码实例展示了如何在Vite项目中使用esbuild.plugins
来配置postcss-pxtorem
,以自动将CSS中的px单位转换为rem单位。rootValue
设置为16,意味着1rem等于16px,这样可以使得根元素的字体大小更容易控制。propList
设置为['*']表示转换所有属性,也可以根据需要指定特定的属性。
评论已关闭