编写postcss插件,全局css文件px转vw
跟目录下创建plugins文件夹,创建postcss-px-to-viewport.ts文件
文件内代码:
// postcss 的插件 vite内置了postCss插件 无需安装
import { Plugin } from 'postcss';interface Options {viewportWidth: number
}const Options = {viewportWidth: 375, // UI设计稿给多少写多少,默认375
}
export const PostCsspxToViewport = (options:Options):Plugin => {const opt = Object.assign({}, Options, options)return {postcssPlugin: 'postcss-px-to-viewport',// 钩子函数Declaration(node) {if (node.value.includes('px')) {const num = parseFloat(node.value);node.value = `${((num / opt.viewportWidth) * 100).toFixed(2)}vw`}}}
}
tsconfig.node.json文件增加plugins引入
{"compilerOptions": {"composite": true,"skipLibCheck": true,"module": "es2022","moduleResolution": "bundler","allowSyntheticDefaultImports": true,"noImplicitAny": false// 允许隐式的any},"include": ["vite.config.ts","plugins/**/*.ts","src/**/*.ts",]
}
vite. config.ts文件中引入PostCsspxToViewport方法