首页 > 语言 > JavaScript > 正文

详解基于Vue/React项目的移动端适配方案

2024-05-06 15:35:35
字体:
来源:转载
供稿:网友

前言

本文的目标是通过下文介绍的适配方案,使用vue或react开发移动端及H5的时候,不需要再关心移动设备的大小,只需要按照固定设计稿的px值布局,提升开发效率。

下文给出了本人分别使用create-react-app搭建的react(create-react-app)项目和使用vue-cli 2.x 搭建的vue项目中的 亲测可用 配置方案。

px2rem或postcss-px2rem

在移动端中,为了设配不同的设备,通常使用rem来做适配。 rem是通过根元素进行适配的,网页中的根元素指的是<html>,我们通过设置<html>的字体大小就可以控制 rem 的大小(1rem = 1根元素字体大小)。 可见,只要我们根据不同屏幕(使用css媒体查询或js)设定好根元素<html>的字体大小,其他已经使用了rem单位的元素就会自适应显示相应的尺寸。 设计稿一般是按照一种特定设备型号(如iphone6)为基础且以px单位来定义样式,为了让设计稿能够通用在不同的设备型号中,则存在着从px到rem的繁琐计算转化过程,因此需要更加科学的方式来使用rem单位。 px2rem或postcss-px2rem的原理:将css中px编译为rem,配合js根据不同手机型号计算出dpr的值,修改<meta>的viewport值和置<html>的font-size。

项目中的使用

recat项目配置postcss-px2rem

首先,我们使用 react 的脚手架 create-react-app 初始化一个 webpack 项目(前提是已经安装过create-react-app,具体不再阐述)。

create-react-app my-app

暴露webpack配置,即 react-scripts 包:

yarn eject

使用yarn 安装项目所需依赖后,安装 lib-flexible 、 postcss-px2rem 和 postcss-loader:

yarn add postcss-px2rem lib-flexible yarn add postcss-loader --dev

在入口页面 index.html 中设置<meta>标签:

<meta name="viewport" content="width=device-width,inital-scale=1.0,  maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">

然后在项目入口文件 index.js 中引入 lib-flexible:

import 'lib-flexible';

接着,在项目config目录下的 webpack.config.js 中引入 postcss-px2rem :

const px2rem = require('postcss-px2rem')

同时,在 webpack.config.js 的 postcss-loader loader里面添加 :

{    loader: require.resolve('postcss-loader'),    options: {     /* 省略代码... */     plugins: () => [      require('postcss-flexbugs-fixes'),      require('postcss-preset-env')({       autoprefixer: {        flexbox: 'no-2009',       },       stage: 3,      }),      px2rem({remUnit: 37.5}), // 添加的内容      /* 省略代码... */     ],     sourceMap: isEnvProduction && shouldUseSourceMap,    },   },

最后,使用 yarn start 重启项目,则会发现项目中的postcss-px2rem配置完成。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选