react移动端项目初始化步骤

408 阅读1分钟

内容来源:React项目实战-《IT猿题库》 | 前端aka老师-你单排吧 (codesohigh.com)

1、依赖安装

使用 npx create-react-app yuantiku 创建完项目后,安装material-ui:

# 用npm安装
$ npm install @material-ui/core

# 用yarn安装
$ yarn add @material-ui/core

# 顺便安装SVG 图标
# 通过 npm
$ npm install @material-ui/icons

# 通过 yarn
$ yarn add @material-ui/icons

 
        Copied!
    

#2、FastClick解决

在 public/index.html 的 head 标签中插入:

<title>IT猿题库</title>
<script src="https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js"></script>
<script>
  if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', function() {
      FastClick.attach(document.body);
    }, false);
  }
  if(!window.Promise) {
    document.writeln('<script src="https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js"'+'>'+'<'+'/'+'script>');
  }
</script>

 
        Copied!
    

这里建议把 as.alipayobjects.com/g/component…as.alipayobjects.com/g/component… 保存到本地

#3、调用

在 App.js 中:

import React, { Component } from 'react'
import Button from '@material-ui/core/Button';

export default class App extends Component {
  render() {
    return (
      <Button variant="contained" color="primary">你好,世界</Button>
    )
  }
}

 
        Copied!
    

然后就可以看到按钮被正式引入:

image-20210428111957851

#4、清除默认边距与样式

npm包路径:www.npmjs.com/package/res…

安装:

$ yarn add reset-css

 
        Copied!
    

使用:

// index.js中
import 'reset-css';

 
        Copied!
    

#四、蓝湖

将设计图用photoshop打开,并上传至蓝湖。此时的设计图是3x尺寸,因此要勾选对应的1125px尺寸。

#五、配置rem

#1、安装依赖包

$ yarn add lib-flexible postcss-pxtorem

 
        Copied!
    

#2、解包

解包需要先做git提交,否则无法解包,因此先执行:

$ git add .
$ git commit -m 'eject之前的提交'

 
        Copied!
    

接下来直接解包:

$ yarn eject

 
        Copied!
    

image-20210425145931070

#3、配置loader

解包后,可以看到项目目录下多了一个 config 文件夹。打开 config/webpack.config.js :

// 引入 postcss-px2rem 
const px2rem = require('postcss-px2rem')

 
        Copied!
    

搜索 postcss-loader ,添加:

const loaders = [
 	 ...,
  {
        // Options for PostCSS as we reference these options twice
        // Adds vendor prefixing based on your specified browser support in
        // package.json
        loader: require.resolve('postcss-loader'),
        options: {
          postcssOptions: {
            // Necessary for external CSS imports to work
            // https://github.com/facebook/create-react-app/issues/2677
            ident: 'postcss',
            config: false,
            plugins: !useTailwind
              ? [
                  'postcss-flexbugs-fixes',
                  [
                    'postcss-preset-env',
                    {
                      autoprefixer: {
                        flexbox: 'no-2009',
                      },
                      stage: 3,
                    },
                  ]],
	              /* -------添加下面这一段------- */
                  [
                    'postcss-pxtorem',
                    {
                      rootValue: 112.5,
                      selectorBlackList: [],
                      propList: ['*'],
                      exclude: /node_modules/i
                    }
                  ],
               	  /* -------添加上面这一段------- */
                  // 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.
                  'postcss-normalize',
                ]
              : [
                  'tailwindcss',
                  'postcss-flexbugs-fixes',
                  [
                    'postcss-preset-env',
                    {
                      autoprefixer: {
                        flexbox: 'no-2009',
                      },
                      stage: 3,
                    },
                  ],
	              /* -------添加下面这一段------- */
                  [
                    'postcss-pxtorem',
                    {
                      rootValue: 112.5,
                      selectorBlackList: [],
                      propList: ['*'],
                      exclude: /node_modules/i
                    }
                  ]
               	  /* -------添加上面这一段------- */
                ],
          },
          sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
        },
  ...
]

 
        Copied!
    

这里的 rootValue: 112.5 的意思就是1rem = 112.5px 这个是根据1125px设计稿来的。

#4、flexible引入

在 入口文件 index.js 里引入 lib-flexible

import 'lib-flexible'

 
        Copied!
    

#5、rem测试

在 App.js 中写个类名,创建 App.css ,并写入:

// App.js
import React, { Component } from 'react'
import './App.css'

export default class App extends Component {
  render() {
    return (
      <div className="box">
        盒子
      </div>
    )
  }
}

// App.css
.box{
    width: 1125px;
    height: 186px;
    background: pink;
}

 
        Copied!
    

接下来打开浏览器:

可以看到,iphoneX的尺寸下,html的字体大小为37.5px,此时box的宽度为10rem,再来看看其他尺寸:

image-20210425154110249

当其他尺寸下时,可以发现html字体大小为41.1px,而此时box的宽度仍为10rem,这就代表我们rem配置成功了。

#6、兼容ipad

但是,当你点开ipad时,会发现盒子兼容出了问题,这是因为淘宝弹性布局方案lib-flexible不兼容ipad和ipad pro。我们这里给出解决方案:

在public>index.html的head标签中添加:

<script>
        /(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));
</script>

 
        Copied!
    

这样,我们就解决ipad的兼容问题了。

#7、修改meta标签

<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />

 
        Copied!
    

#六、配置less

#1、安装

$ yarn add less less-loader@5.0.0
# 或者
$ npm install less less-loader@5.0.0

 
        Copied!
    

#2、解包

接下来要解包,如果上一步你已经解包过,就直接跳过。

如果未解包,请以上参考第五步。

#3、配置loader

找到 webpack.config.js ,搜索 sassRegex

const lessModuleRegex = /.less$/;

 
        Copied!
    

搜索 sass-loader 后,在其下方添加:

module: {
  ...,
  // less加载器 
	{
    test: lessModuleRegex,
    use: getStyleLoaders(
        {
            //暂不配置
        },
        'less-loader'
    ),
	},
}

 
        Copied!
    

修改了配置文件,记得重新 yarn start 哦!

#4、测试less

将 App.css 改为 App.less 进行测试,依然没问题。

#5、文字三属性

在 App.less 中添加:

@import url("http://at.alicdn.com/t/font_2390471_h1demfeh4rc.css");

#root {
    font-size: 38px;
    font-family: NotoSansHans;
    color: #333333;
}

 
        Copied!
    

这里注意,由于html和body标签已被强行设定了font-size,因此我们设定#root的font-size即可