手工創建react項目

react的開發者都知道使用create-react-app創建項目,這是非常簡單的,但不是本文的目的,本文將帶你如何一步一步搭建react項目。

1、初始化項目,編寫組件

執行下面命令初始化項目

npm init -y

安裝react、react-dom

npm -i -D react react-dom

在根目錄下創建src文件夾,並在src文件夾裏面創建index.js、index.css文件,他們兩分別是組件和組件所需樣式

// index.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'

import './index.css'

class App extends Component {
  // 類屬性寫法是js實驗特性
  state = {
    textInput: null
  }

  textInputFocus = (element) => {
    this.textInput = element
  }
  // 此箭頭函數寫法是js實驗特性
  handleClick = () => {
    this.textInput.focus()
  }

  render () {
    return (
      <div className="div-box">
        <input type="text" ref={this.textInputFocus}/>
        <input type="button" value="focus" onClick={this.handleClick}/>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
// index.css
.div-box {
  width: 500px;
  height: 500px;
  border: 1px solid #000;
  box-sizing: border-box;
}

2、配置webpack+babel

瀏覽器是不支持JSX語法,而且上面index.js中還是用了js實驗特性,目前還沒有被ECMAScript所採納,也是需要babel轉譯。我們還需要處理css樣式或者其他樣式規格,最後打包成js引入到生成的html文件中。

安裝相關依賴:

npm i -D webpack 
webpack-cli 
webpack-dev-server 
@babel/core 
@babel/plugin-proposal-class-propertiese 
@babel/cli 
@babel/preset-env 
@babel/preset-react
@babel/runtime 
@babel/plugin-transform-runtime 
babel-loader 
css-loader 
style-loader 
html-webpack-plugin 
clean-webpack-plugin

對其中有些依賴做個說明,webpack-dev-server幫助我們實時打包文件,只要文件改動就重新打包。@babel/plugin-proposal-class-propertiese轉譯js實驗特性,比如類裏面定義的屬性和箭頭函數。@babel/preset-react幫助轉譯JSX語法。html-webpack-plugin幫助生成html,並將打包後的js引入。clean-webpack-plugin每次打包都會將上次打包的文件清除。
鏈接:https://www.npmjs.com/package/@babel/plugin-proposal-class-properties

在根目錄下創建webpack.config.js配置webpack

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
    app: './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: '[name].bundle.js',
    publicPath: './',
    chunkFilename: '[name].js'
  },
  module: {
    rules: [
      // 處理js、jsx
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader'
        }]
      }, 
      // 處理樣式
      {
        test: /\.css$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          }
        ]
      }
    ]
  },
  optimization: {

  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '主文件',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        minifyCSS: true
      },
      filename: 'index.html',
      template: path.resolve(__dirname, 'index.html'),
      chunks: ['app']
    })
  ]
}

在根目錄下創建.babelrc配置babel

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-proposal-class-properties" // 該插件可轉換靜態類屬性以及使用屬性初始值設定項語法聲明的屬性
  ]
}

在根目錄下創建idnex.html模板

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

3、配置eslint

安裝依賴

npm i -D eslint

執行npx eslint --init在根目錄下生成.eslintrc.js配置文件,交互生成過程中選擇react

如果現在去校驗src目錄文件的代碼規範將會報錯,因爲目前eslint只支持ES6/ES2015,不支持spread object語法,經查發現spread objectES7規範(還包括class properties,decorators,async/await

2.png

這條錯誤指的是

3.png

安裝babel-eslint

npm install babel-eslint --save-dev

倘若需要支持generator-star,object-shorthand等特性,需要安裝eslint-plugin-babel

npm install eslint-plugin-babel --save-dev

然後在配置文件.eslintrc.\* 添加如下配置

module.exports = {
  env: {
    browser: true,
    es6: true
  },
  extends: [
    'standard',
  ],
  globals: {
    Atomics: 'readonly',
    SharedArrayBuffer: 'readonly'
  },
  parser: "babel-eslint",
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
      experimentalObjectRestSpread: true
    },
    ecmaVersion: 2018,
    sourceType: 'module'
  },
  plugins: [
    'react',
    'babel'
  ],
  rules: {
  },
}

現在檢查代碼規範將報如下錯誤:
4.png
解決方法

extends: [
    'standard',
    'plugin:react/recommended' // 添加react插件推薦規則
],

或者在rule中添加如下重寫如下規則:

rules: {
    "react/jsx-uses-react": 1, // 處理組件中React未被使用
    "react/jsx-uses-vars": 1 // 使用組件App未被使用
  },

再次檢查代碼規範又會報一條警告:

React version not specified in eslint-plugin-react settings

說在 eslint-plugin-react中沒有指定react版本

這裏我們通過給所有規則配置共享設置來解決:

如何添加共享設置:https://eslint.org/docs/user-guide/configuring#adding-shared-settings

.eslintrc.js加上下面設置

settings: {
    react: {
      // 修復警告:React version not specified in eslint-plugin-react settings
      version: require('./package.json').devDependencies.react
    }
  }

最後,爲了運行方便,我們在package.json中添加腳本

"scripts": {
    "build": "webpack --mode production",
    "start": "webpack-dev-server --open",
    "lint": "eslint ./src",
    "lint:watch": "esw -w ./src"
},

其中,配置lint:watch需要先安裝eslint-watch插件,該插件幫助我們實時檢測代碼規範,就跟webpack-dev-server幫助我們啓動服務實時打包一樣。

現在我們來打包運行看看:

5.png

瀏覽器打開生成的index.html

6.png

執行eslint看看

7.png

簡直完美!

參考:
如何創建react項目:
https://mingjiezhang.github.io/2017/06/16/%E7%BF%BB%E8%AF%91-%E6%80%8E%E4%B9%88%E5%86%99%E4%B8%80%E4%B8%AAReact%E7%BB%84%E4%BB%B6%E5%BA%93%EF%BC%88%E4%B8%80%EF%BC%89/
https://dev.to/vish448/create-react-project-without-create-react-app-3goh
eslint如何支持ES7語法校驗
https://github.com/garylgh/blog/blob/master/source/_posts/Eslint%E5%BC%80%E5%90%AFES7%E8%AF%AD%E6%B3%95%E6%A0%A1%E9%AA%8C.md
組件中React導入了但沒有被使用,eslint檢測報錯
https://github.com/babel/babel-eslint/issues/6
修復警告:React version not specified in eslint-plugin-react settings
https://github.com/yannickcr/eslint-plugin-react/issues/1955

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章