環境建置

在進入 React 開發環境之前,需要先安裝 webpack 和 babel。

webpack 安裝

因為 React 會用到 import 語法,所以需要 webpack 來幫忙 bundle 程式碼。

  • 前往目標資料夾,進行 npm 的初始化
  • 安裝 webpackwebpack-cli
$ npm init  // 目標資料夾內自動產生 package.json
$ npm install webpack webpack-cli --save-dev
  • 新增檔案 utils.js,然後 export 一個 log(),放進 src 資料夾
export function log(str) {
    console.log(str)
}
  • 新增檔案 index.js,然後 import 剛剛新建立的 log(),放進 src 資料夾
import {log} from '.utils'
log('hello world')
  • 接下來處理 webpack 設定檔
    • 新增一個 webpack.config.js,webpack 打包時會先去看這個檔案
const path = require("path")

module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.join(__dirname, "/dist"),
        filename: 'bundle.js'
    }

}  // export 一個 json 格式檔(物件)
  • 打開 package.json,在 script 新增 startbuild 任務
"scripts": {
    "start": "webpack --mode development",
    "bulid": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  • 接著在 terminal 輸入 npm run start
$ npm run start
  • 資料夾下會新增一個 dist 資料夾,裡面會有一個打包好的 bundle.js 的檔案
  • 接著將 bundle.js引入至 index.html
  • 打開 index.html 確認自己是否打包成功
<script src="./dist/bundle.js"></script>

babel 安裝

React 會用到 ES6 的語法,但很多瀏覽器還沒有支援 ES6 的語法,所以我們要透過 babel 轉成 ES5 語法。

  • 安裝 @babel/core@babel/preset-env、 babel-loader(webpack 使用)
$ npm install babel-loader @babel/core @babel/preset-env --save-dev
  • 新增一個 babel 的設定檔 .babelrc
{
  "presets" : ["@babel/preset-env"], // 支援大部分現代瀏覽器
}
  • 如何將 babel 融入 webpack 打包的流程
    • 打開 webpack.config.js ,設定 loader
module: {
        rule: [
            {
                test: /.js$/,   
                exclude: /node_nodules/, 
                use: {
                    loader: 'babel-loader'
                } 
            }
        ]
    }
// exclude: /node_nodules/ 資料夾底下的有先轉譯,這樣要花很久時間,所以先排除掉
// 針對 .js 結尾的檔案,用 babel.loader 把程式碼轉成 ES5 再 loading 進來

加入 React

  • 安裝 react
    • 因為 React 之後會使用 JSX,所以仍需要 babel 的幫忙
$ npm install react react-dom @babel/preset-react
  • 更改 .babelrc 的 babel 規則
{
  "presets" : ["@babel/preset-env", "@babel/preset-react"],
}
  • src 的資料夾內,新增 app.js 檔案
import React, {Component} from 'react'

class App extends Component {
  render() {
    return (
      <h1>Hello React</h1>
    )
  }
}

export default App
  • 打開 index.js,更新內容
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(<App />, document.getElementByID('root'))
// 把 App 這個 compnent 給 render 到 #root 的 DOM 裡面。

Webpack dev server

第一個優化:檔名加入 hash 防止被 Cache

保證載入的檔案,永遠是最新的檔案。

  • 編輯 webpack.config.js
    hash 之後的新檔名為:bundle.be3071687684584a91d1.js
filename: 'bundle.[hash].js'
  • 另外一個問題是,index.html 要如何確保檔案名稱可以同步更新
    • 安裝 html-webpack-plugin
$ npm install html-webpack-plugin
  • 修改 webpack.config.js
    • 原本的 index.html 裡面的引入 script 刪除
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin'); // import  進來

module.exports = {
  entry : './src/index.js',
  output : {
    path: path.join(__dirname, '/dist'),
    filename : 'bundle.[hash].js'
  },
  plugins: [
    new htmlWebpackPlugin({
      template: './index.html' // template 的位置為 index.html
    })
  ]
}
  • 在 terminal上 npm run start,會發現 dist 資料多了一個 index.html
  • 打開 dist 資料夾底下的 index.html,就會發現 webpack 幫我們加上有 hash 過後的 js 檔案

第二個優化:webpack-dev-server 網頁自動更新

每次修改檔案,都要重新 build 打包,是不是有更方便的指令,讓我們儲存檔案之後,會自動更新?

  • 有喔!來安裝 webpack-dev-server
$ npm install webpack-dev-server
  • 修改 package.json 裡面 start 的指令
 "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production",
  },

環境建置-極速版

React 官方推薦的懶人包安裝法。

npx create-react-app my-app
cd my-app
npm start







你可能感興趣的文章

Insert Sort

Insert Sort

[BE101] 資訊安全

[BE101] 資訊安全

【Day07】透過Github將個人網頁上架至Netlify靜態網站服務

【Day07】透過Github將個人網頁上架至Netlify靜態網站服務






留言討論