Lidemy / mentor-program-2nd-futianshen

mentor-program-2nd-futianshen created by GitHub Classroom
14 stars 2 forks source link

搭建 React 開發環境 #37

Open futianshen opened 5 years ago

futianshen commented 5 years ago
  1. Git 初始化

    git init vim .gitignore

  2. Yarn 初始化

    yarn init

  3. 設定 Webpack

    yarn add webpack webpack-cli html-webpack-plugin webpack-dev-server

    webpack.config.js(webpack 設定檔)
    const path = require('path')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
      mode: 'development',
      entry: './src/index.js',
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
          }
        ]
      },
      output: {
        filename: 'bundle.[hash].js', // 防止瀏覽器 cache bundle.js
        path: path.resolve(__dirname, 'dist'), // .join 和 .resolve 有什麼差別 ? 'dist' of '/dist'
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: './index.html' // 讓每次自動產生的 bundle.[hash].js 不需要手動重新引入 index.html
        })
      ]
    }

    使用 Webpack 的方法

    1. npx webpack
    2. yarn run start:hot
      package.json
        "scripts": {
          "start:hot":"webpack-dev-server --mode development --open --hot",
        }
    3. yarn run start
      package.json
        "scripts": {
          "start": "webpack --mode development"
        }
    4. yarn run build
      package.json
        "scripts": {
          "build": "webpack --mode production"
        }
  4. 設定 Babel

    yarn add @babel/core @babel/preset-env @babel/preset-react @babel/plugin-proposal-class-properties babel-loader

    .babelrc (告訴 babel 有那些格式要轉換)

    {
      "presets": ["@babel/preset-env", "@babel/preset-react"], /*  */
      "plugins": ["@babel/plugin-proposal-class-properties"]
    }
  5. 設定 React

    yarn add react react-dom react-hot-loader

    src/app.js

    import React from 'react'
    import { hot } from 'react-hot-loader'
    
    class App extends React.Component { 
      constructor (props) { 
        super(props) 
        this.state = {
          // 初始狀態
          hello: 'Hello, World'
        }
      }
    
      render () {
        return (
          <div>
            <h1>{this.state.hello}</h1>
            {/* render */}
          </div>
        )
      }
    } 
    export default hot(module)(App)

    src/index.js

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App.js'
    
    ReactDOM.render( 
      <App />,
      document.getElementById('root')
    )