react使用 postcss-px-to-viewport 转换

react 项目中css样式px自动转vw,适配移动端和pc端。修改下配置项里面的viewportWidth和viewportHeigh

  • 安装:postcss-px-to-viewport 和 postcss-loader
//1.npm方式:
npm install postcss-loader postcss-px-to-viewport --save-dev

//2.yarn安装:
yarn add -D postcss-loader postcss-px-to-viewport
  • 二:暴露项目配置项(任选一种)
若报错,有git的可以通过 
    git add .
    git commit -m '暴露项目配置项'
    npm run eject
npm方式:
    npm run eject

cnpm方式:
    cnpm run eject
    
yarn方式:
    yarn eject
  • 【3】配置 webpack.config.js
    • 文件内搜索(100行左右位置):const getStyleLoaders = (cssOptions,
    • 查看webpack配置代码版本,这里有两种版本样式,配置稍有点区别
      • 若结构是这样的,使用该配置方式


        image
[
  'postcss-px-to-viewport',
  {
    
    viewportWidth: 750, // (Number) The width of the viewport.
    viewportHeight: 1334, // (Number) The height of the viewport. -- 一般不需要配置
    unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
    viewportUnit: "vw", // (String) Expected units.
    selectorBlackList: [], // (Array) The selectors to ignore and leave as px.
    minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
    mediaQuery: false // (Boolean) Allow px to be converted in media queries.
  }
],
  • 2.其他的方式:
require('postcss-px-to-viewport')({
    
  viewportWidth: 750, // (Number) The width of the viewport.
  viewportHeight: 1334, // (Number) The height of the viewport. -- 一般不需要配置
  unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
  viewportUnit: "vw", // (String) Expected units.
  selectorBlackList: [], // (Array) The selectors to ignore and leave as px.
  minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
  mediaQuery: false // (Boolean) Allow px to be converted in media queries.
}),
  • 最后效果


    img
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容