安装postcss-px-to-viewport
npminstallpostcss-px-to-viewport-S
配置webpack.config.js或者package.json(二选一即可)
- 方法一:配置webpack.config.js
constpostcssPxToViewport=require('postcss-px-to-viewport'); // 引入自适应插件{ // Options for PostCSS as we reference these options twice// Adds vendor prefixing based on your specified browser support in// package.jsonloader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work// https://github.com/facebook/create-react-app/issues/2677ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), require('postcss-preset-env')({ autoprefixer: { flexbox: 'no-2009', }, stage: 3, }), // Adds PostCSS Normalize as the reset css with default options,// so that it honors browserslist config in package.json// which in turn let's users customize the target behavior as per their needs.postcssNormalize(), // 这是要增加的部分postcssPxToViewport({ viewportWidth: 1920, // 设计稿宽度unitPrecision: 5, // px转换后的小数保留位数,有时候不能整除minPixelValue: 1, // 小于或等于`1px`时不转换为视窗单位 }) ], sourceMap: isEnvProduction?shouldUseSourceMap : isEnvDevelopment, }, },
- 方法2:配置package.json\
"postcss": { "plugins": { "autoprefixer": {}, "postcss-px-to-viewport": { "viewportWidth": 1920, // 设计稿宽度"unitPrecision": 5, // px转换后的小数保留位数,有时候不能整除"minPixelValue": 1// 小于或等于`1px`时不转换为视窗单位 } } }
其他配置可以自行查询如下列属性等:
mediaQuery: false, // 允许在媒体查询中转换,默认为falsepropList: ["*"], // 转化为vw的属性列表viewportUnit: "vw", // 指定转换的单位fontViewportUnit: "vw", // 字体使用的单位selectorBlaskList: [".ignore-"], // 指定不需要转换的类
postcss-px-to-viewport的缺点
postcss-px-to-viewport虽然好用,但是却有一个缺点,就是只对style内的样式进行转换,行内样式没办法转换,我还没解决,因为我没写行内样式