macOS下配置React Native开发环境的正确姿势

TL.DR

Homebrew -> watchman
nvm -> Node.js -> npm -> react-native-cli -> react-native

Heads up

JS的世界是疯狂的。

2015年facebook在React.js Con上首次推出React Native时,Node.js的版本号是0.11.x,两年半后的今天已经狂飙突进到了8.5.0。
macOS下配置React Native开发环境的正确姿势_第1张图片

在这种时候,不论是前端老司机,还是刚刚接触JS的跨界开发者,都需要一根安全带——

nvm

Node Version Manager,支持安装多个Node版本并可自由切换,居家旅行必备。
安装过程有点曲折。尽管Homebrew中可以搜到nvm的formula,但官方并不支持通过它安装,look

Homebrew installation is not supported. If you have issues with homebrew-installed nvm, please brew uninstall it, and install it using the instructions below, before filing an issue.

最简单的安装方式是

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.4/install.sh | bash
#or
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.4/install.sh | bash

注意链接中包含了nvm的版本号,当你读到这里时很可能nvm已经有了更新的版本,你可以从官方repo的README中获取最新的链接。

如果你用zsh的话,那么zsh-nvm会是更好的选择。

Node.js && npm

通过nvm安装最新的Node.js LTS版本

nvm install --lts

#安装成功后查看node版本
node -v
v6.11.3

设置npm指向淘宝镜像,原因你懂的

echo 'registry https://registry.npm.taobao.org' > ~/.npmrc

Node自带的npm往往不是最新的,更新先

npm install -g npm@latest

react-native-cli

react-native-cli是一个npm package

npm install -g react-native-cli

它的核心作用是生成React Native工程。

react-native init hello_react_native

以及启动app

cd hello_react_native

#这个command只做2件事,在app这一边
#1. 调用xcodebuild编译iOS工程,把生成的.app安装到Simulator里
#2. 启动Simulator
#3. 启动app
#在Node.js这边
#1. 启动React Native Packager
react-native run-ios

watchman

上文提到的React Native Packager,会利用watchman监听工程目录下js文件的变化,并通知运行中的app,以实现Hot Reload。

brew install watchman

如果安装后Homebrew提示postinstall failed,很可能是因为/usr/local目录的权限不对,需要

sudo chown -R whoami /usr/local

运行

react-native run-ios

一切顺利的话,Simulator里应该已经跑起了模板app


macOS下配置React Native开发环境的正确姿势_第2张图片

Optional:Visual Studio Code

facebook推荐使用nuclide,但在开发工具上,我选择做一只软。React Native Tools 是微软专门为React Native提供的VSC扩展,稳定可靠。

你可能感兴趣的:(macOS下配置React Native开发环境的正确姿势)