AdSense

網頁

2021/7/20

React 使用Create React App建立React應用程式

Create React App是React官方支援的建立React應用程式/專案工具,下面以此工具建立一個簡單的Hello World React應用程式。


範例環境:

  • macOS Big Sur (v11.4)
  • node v16.5.0
  • npm 7.19.1


事前要求

使用Create React App建立React前電腦中必須安裝好node.js及npm


建立React專案

在命令列輸入npx create-react-app <app_name>建立React應用程式,<app_name>為專案名稱。

例如下面輸入npx create-react-app app建立一個專案名稱為app的React應用。若尚未安裝create-react-app套件會提示安裝,輸入y安裝。

$ npx create-react-app app
Need to install the following packages:
  create-react-app
Ok to proceed? (y) y

Creating a new React app in .../app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

...

Success! Created app at .../app
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd app
  npm start

Happy hacking!
...

執行完後可在執行所在目錄看到新增的app資料夾,此即為React專案的根目錄。


啟動React

在專案跟目錄/app下輸入npm start啟動React應用程式。

.../app$ npm start

若專案是從github clone下來則可能會出現react-scripts: command not found無法啟動,需要在/app下執行npm install下載需要的module。

.../app$ npm start

> app@0.1.0 start
> react-scripts start

sh: react-scripts: command not found

啟動成功顯示以下訊息。

Compiled successfully!

You can now view app in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.1.102:3000

Note that the development build is not optimized.
To create a production build, use npm run build

然後會在瀏覽器開啟localhost:3000顯示預設頁面如下。




修改首頁

專案目錄中的/public/index.html為主頁面的樣板(template),簡單說就是React render的地方。

/src/index.js則為React的JavaScript進入點,負責把App元件render到index.html<div id="root"></div>。而App元件為/src/App.js中的function App() {...},即為預設頁面的內容

開啟src/App.js修改App() return的內容如下存檔。

App.js

import './App.css';

function App() {
  return <h1>Hello, world!</h1>
}

export default App;

存檔後預設頁面的畫面變成以下。




github


沒有留言:

AdSense