当前位置: 首页 > 工具软件 > px2rem > 使用案例 >

适配移动端配置px2rem(自动将px转rem)

尤研
2023-12-01

vue配置px2rem

1、安装

npm install px2rem-loader lib-flexible –save

2、在项目入口文件main.js中引入lib-flexible

import ‘lib-flexible/flexible.js’

3、在build下的 utils.js中,generateLoaders 方法。

const px2remLoader = {
  loader: 'px2rem-loader',
  options: {
    remUnit: 75 // 设计图的1/10
  }
}
function generateLoaders (loader, loaderOptions, anotherLoader) {
  const loaders = options.usePostCSS ? [cssLoader, postcssLoader,px2remLoader] : [cssLoader,px2remLoader]

  if (loader) {
    loaders.push({
      loader: loader + '-loader',
      options: Object.assign({}, loaderOptions, {
        sourceMap: options.sourceMap
      })
    })
  }
  if (!!anotherLoader) loaders.push(anotherLoader)

  // Extract CSS when that option is specified
  // (which is the case during production build)
  if (options.extract) {
    return ExtractTextPlugin.extract({
      use: loaders,
      fallback: 'vue-style-loader'
    })
  } else {
    return ['vue-style-loader'].concat(loaders)
  }
}

小程序配置px2rem

H5转rem,小程序是rpx,统一配置:npm install px2rpx-loader

const px2remLoader = {
  loader: 'px2rem-loader',
  options: {
    remUnit: 75 // 设计图的1/10
  }
}
const px2rpxLoader = {
  loader: 'px2rpx-loader',
  options: {
    baseDpr: 1,
    rpxUnit: 1
  }
}

react配置px2rem(react-create-app的基础上)

首先,下载

npm i lib-flexible postcss-px2rem-exclude --s

然后,webpack.config.js

const px2rem = require('postcss-px2rem-exclude');

找到postcss-loader

{

  loader: require.resolve('postcss-loader'),
  options: {
   
    ident: 'postcss',
    plugins: () => [
      require('postcss-flexbugs-fixes'),
      require('postcss-preset-env')({
        autoprefixer: {
          flexbox: 'no-2009',
        },
        stage: 3,
      }),
        //px2rem 修改地方
        px2rem({remUnit:75,exclude:/node_modules/i})
    ],
    sourceMap: isEnvProduction && shouldUseSourceMap,
  },
},

最后在index.js

//px2rem
import 'lib-flexible/flexible'
 类似资料: