React Native學習筆記(一)Mac OS X下React Native的環境搭建
本文介紹Mac OS X系統下的React Native環境搭建過程。
1.環境要求:
1) Mac OS X作業系統
2) Xcode6.4或以上版本
3) Node.js4.0或以上版本
4) watchman和flow
2.安裝過程
1) Node.js的安裝可以在Node.js的官網https://nodejs.org/ 中下載最新的版本。這裡下載的是node-v4.4.2.pkg版本。直接雙擊執行安裝就可以了。檢視是否安裝成功可以在終端中輸入如下命令:
$node -v
如果能夠顯示版本資訊,則表明安裝成功。
2) watchman和flow的安裝:watchman是用來監控檔案變化的,flow是進行型別檢查的。推薦使用Homebrew安裝,終端命令:
$ brew install watchman
$ brew install flow
3) 通過npm安裝react-native-cli命令列工具。
$npm install -g react-native-cli
其中-g這個引數表示全域性安裝。
如果在安裝過程中需要管理員許可權,可是給命令新增sudo,然後輸入管理員密碼。如下:
$sudo npm install -g react-native-cli
至此環境已經搭建完。我們可以建立一個小Demo來檢測一下環境搭建的是否成功。
3.建立React Native工程
使用下面這個命令建立一個React Native的專案工程檔案
react-native init AwesomeProject
出現上面的提示,說明環境配置的沒有問題。
4.執行專案工程
這裡有兩種執行方式,任選其一就可以。
1)使用命令列的方式,在終端中輸入如下命令:
$react-native run-ios
2)找到AwesomeProject.xcodeproj檔案,然後雙擊開啟,com + R直接執行。
5.可能遇到的問題
對於這個Demo而言,官網上的教程好像到這裡就可以運行了。可是本人第一次並沒有執行成功,而是在手機整個螢幕上出現了紅色的錯誤提示。
1)在delegate中伺服器的地址並沒有替換,如下:
/**
* Loading JavaScript code - uncomment the one you want.
*
* OPTION 1
* Load from development server. Start the server from the repository root:
*
* $ npm start
*
* To run on device, change `localhost` to the IP address of your computer
* (you can get this by typing `ifconfig` into the terminal and selecting the
* `inet` value under `en0:`) and make sure your computer and iOS device are
* on the same Wi-Fi network.
*/
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
在上面的註釋中有明確的說明,需要將localhost換成本地計算機的ip地址。而且檢視的方法也給出了,在終端中輸入如下命令:
$ ifconfig
然後尋找en0:下的IP地址,完成localhost為本機ip地址的替換。
2)需要確定Node Serve服務已經正在執行
可以執行npm start命令。有時候執行這個命令,可能8081埠被別的程序佔用了,如下圖:
可以根據提示執行下面的命令,找出佔用8081埠的程序
lsof -n -i4TCP:8081
使用下面的命令關閉該程序:
$ kill -9 90587
其中:這個命令的語法為:
$ kill -9 <PID>