background

Recently because to do a new project management of the background, the new company is mostly written in vue, technique is to stack the cut to react to above, so, this time from 0 to 1 to set up a react project shelves, and a lot of things to consider, including the directory structure, standard code, request to packaging, etc., which involves many contents, So I divided it into several parts to record the construction process:

  1. React + ANTD +redux: React + ANTD +redux
  2. React + ANTD + Redux
  3. React + ANTd +redux
  4. React + ANTd +redux

I have uploaded the project to Github. If you need it, please help yourself. Remember star! You are also welcome to mention issue~ above

  • react-antd-adminMT

Project initialization

  1. Create projects using create-React-app and typescript templates
yarn create react-app react-antd-adminMT  --template typescript
Copy the code
  1. Directory structure adjustment

To facilitate the development and management of the code, we create subfolders of Components, Navigation, Pages, redux, Services, utils under SRC

├ ─ ─ LICENSE ├ ─ ─ the README. Md ├ ─ ─ build ├ ─ ─ the mock - local mock services │ ├ ─ ─ for server js │ └ ─ ─ test. The js ├ ─ ─ package. The json ├ ─ ─ public ├ ─ ─ SRC │ ├─ Components │ ├─ Config - Configuration files │ ├─ index.css │ ├─ index.tsX │ ├─ Navigation │ ├─ Pages │ ├─ ├─ exercises - ├─ exercises - ├─ exercises - ├─ exercises - ├─ exercises - ├─ exercises - ├─ exercises - ├─ tsconfig.json └ ─ ─ yarn. The lockCopy the code

Multi-environment packaging configuration

For example, we need to configure several different environments and load different variables

.env.development
.env.staging
.env.production
Copy the code

Each file has a different variable value

PORT=3000
REACT_APP_ENV=staging
REACT_APP_BASE_URL=https://www.zhihu.com
Copy the code

Load different environment variable files when packaging

Two ways:

  • env-cmd
  • dotenv-cli
"scripts": {
    "dev": "env-cmd -f .env.development react-scripts start"."dev:stg": "env-cmd -f .env.staging react-scripts start"."build": "react-scripts build"."build:stg": "env-cmd -f .env.staging yarn build"."build:prod": "env-cmd -f .env.production yarn build"."test": "react-scripts test"."eject": "react-scripts eject"
  },
Copy the code

Env-cmd is used here. Env-cmd is used to configure env-cmd-f. env.development in the script command, so that we can load variables in the. Env.development file when we do yarn dev. Each different environment package load corresponds to a different environment variable

Configuration code specification

Prettier with eslint

Eslint is used mainly for syntax verification, while Prettier maintains style uniformity

  1. Installing related packages
$ yarn add C eslint-plugin-prettier eslint-config-prettier --dev
Copy the code

Eslint, Prettier are definitely necessary in the installation package above. The eslint-plugin-prettier plugin calls Prettier to check your code style. Eslint-config-prettier can turn off lint options that aren’t necessary or conflict with Prettier

  1. Create the.eslintrc.js file in the root directory
module.exports = {
  root: true.parserOptions: {
    ecmaFeatures: {
      jsx: true}},env: {
    browser: true.es6: true
  },
  extends: ['react-app'.'plugin:prettier/recommended'].plugins: ['prettier'].rules: {
    'prettier/prettier': 'error'.'react-hooks/rules-of-hooks': 'error'.'react-hooks/exhaustive-deps': 'off'}}Copy the code

There are many ESLint configuration items, such as Parser, parserOptions, Environments, Globals, Plugins, extends, and Rules

Details can see eslint.bootcss.com/docs/user-g eslint manual…

This article focuses on the extends, plugins, and Rules options

  1. extends

A configuration file can inherit enabled rules from the underlying configuration. Extends introduces shared configuration packages and plug-ins

  • Shareable configuration

The shareable configuration is an NPM package that outputs a configuration object. The extends property value can omit the prefix eslint-config- of the package name.

  • The plug-in

A plug-in is an NPM package that typically outputs rules. The plugins attribute value can omit the package name prefix eslint-plugin-.

  • The extends property value can be composed of:

(1), plugin: (2), package name (omit prefix, e.g. React) (3), / (4), configuration name (e.g. Recommended) [‘react-app’, ‘plugin:prettier/recommended’]

  1. plugins

ESLint supports the use of third-party plugins. Before using the plugin, you must install it using the package management tool, and the plugin name can omit the eslint-plugin- prefix

  1. rules

ESLint comes with a lot of rules and you can use comments or configuration files to modify the rules you want to use in your project. To change a rule setting, you must set the rule ID to either OFF, WARN, or ERROR.

  1. Create the. Prettierrc.js file in the root directory
module.exports = {
    semi: false.// Add a semicolon at the end of a sentence
    singleQuote: true.// Use single quotes
    printWidth: 80.// Newline string threshold
    jsxSingleQuote: true.// Use single quotes instead of double quotes in JSX
    trailingComma: 'none'.// Add a comma to the last object element
    arrowParens: 'avoid'    // (x) => {} whether to include parentheses
}
Copy the code

  1. After configuring ESLint and Prettier above, but to format automatically, we need to do some integration. For example, you can format your code automatically after your changes are saved

Open the VScode configuration file and add the following configuration

{
  "eslint.alwaysShowStatus": true."editor.formatOnSave": true."[javascript]": {
    "editor.formatOnSave": false
  },
  "[html]": {
    "editor.formatOnSave": false
  },
  "editor.formatOnPaste": false."editor.tabSize": 2."javascript.updateImportsOnFileMove.enabled": "never"."editor.codeActionsOnSave": {
    "source.fixAll.eslint": true}}Copy the code

Add the configuration above because it is global, to make it uniform for team development, we can also configure it separately for the project, create the.vscode folder in the root directory of the project and create a new settings.json file, then copy the above contents into it

Configuration husky

Husky is a Git hooks tool that does something when we commit or push code to make sure that the code we commit is compliant

  1. Install the husky
$ yarn add husky --dev
Copy the code
  1. Set the Git hooks we need in package.json
"husky": {
    "hooks": {
      "pre-commit": "lint-staged".// Check the temporary files for rule verification before commit
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS".// Verify that the remarks added during commit comply with our requirements}},Copy the code

Here we need to install the following packages

$ yarn add @commitlint/cli @commitlint/config-conventional lint-staged eslint-plugin-simple-import-sort -D
Copy the code

Lint-staged code rules check before committing code into a Git repository to ensure that it is written in accordance with code rules. Lint-staged code can be fast enough to only detect files in staging if it would be slow to run Lint through the project.

Commitlint /cli @commitlint/ config-Conventional, these two are mainly used to standardize the code submission information

Type The following types are supported:

  • Build: The main purpose is to modify the commit of the project build system (e.g. glUP, Webpack, rollup configuration, etc.)
  • Ci: The main purpose is to modify the submission of the project to continue the integration process (e.g. Travis, Jenkins, GitLab CI, Circle, etc.)
  • Docs: Updates the document
  • Feat: Added function
  • Fix: Fixes bugs
  • Perf: Performance optimization
  • Refactor: Refactoring code (no new features, no bug fixes)
  • Style: Code changes that do not affect program logic (modify whitespace characters, complete missing semicolons, etc.)
  • Test: Add a test case or update an existing test
  • Revert: Rolls back an earlier submission
  • Chore: Any other type that is not one of the above (chore)

Such as:

$ git commit -m 'Feat: Add XXX feature'
$ git commit -m 'fix: fix xxxbug'
Copy the code

If you do not comply with the above specification to support Type, an error will be reported when submitting

  1. Create the.lintStagedrC.js file in the root directory
module.exports = {
  '**/*.{js,jsx,ts,tsx}': [
    'prettier --write'.'eslint --fix --plugin=simple-import-sort --rule=simple-import-sort/imports:error'.'git add'].'**/*.{json,md,mdx,css,html,yml,yaml,scss}': ['prettier --write'.'git add']}Copy the code
  1. Create a. Commitlintrc. json file in the root directory
{
  "extends": [
    "@commitlint/config-conventional"]}Copy the code
  1. Finally, note that when husky is configured, the commit does not take effect, and it is husky version 6.0 that has made a destructive update. This is resolved by removing the husky package and adding the lower version
$ yarn remove husky 
$ yarn add husky@4.38. -D
Copy the code

Http Request encapsulation

  1. A new apiclient.js file is used to configure AXIOS and finally returns an axiOS instance
import axios from 'axios'

const baseURL = process.env.REACT_APP_BASE_URL

const instance = axios.create({
  baseURL,
  timeout: 15000
})

// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)

export default instance
Copy the code
  1. Introduce apiClient and call axios’s request method
import apiClient from './apiClient'

export const getContractList = () = > apiClient.get(`/api/v4/search/top_search`)
Copy the code
  1. Get and POST parameter transfer

A get request requires a params field to be passed as a parameter

/ / get request
axios.get('/user', {
    params: {
      ID: 12345}})/ / post request
axios.post('/user', {
    firstName: 'Fred'.lastName: 'Flintstone'
  })
Copy the code

Local cross-domain request

Create a setupproxy.js file in the SRC directory to configure the proxy interface, so that we can proxy to the http://localhost:3001 service when requesting/proxy-API, thus solving the cross-domain problem

const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = function (app) {
  app.use(
    '/proxy-api',
    createProxyMiddleware({
      target: 'http://localhost:3001'.changeOrigin: true.secure: false.pathRewrite: {
        '^/proxy-api': ' ' // Remove/API from request}}}))Copy the code

Build the local Mock service

  1. Create a mock folder in the root directory and create a new server.js file. Here I use Express to start a Node service
const express = require('express')
const app = express()
const port = 3001

app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.get('/'.(req, res) = > {
  res.send('Hello World! ')})// Load the route
app.use('/api'.require('./test'))

app.listen(port, () = > {
  console.log(`mock server listening at http://localhost:${port}`)})Copy the code
  1. Interface routing that returns mock data
var express = require('express')
var router = express.Router()
// http://mockjs.com/
var Mock = require('mockjs')

router.get('/hello'.function (req, res) {
  res.json({ user: 'hello' })
})

router.get('/mock'.function (req, res) {
  console.log(req.body)
  var data = Mock.mock({
    top_search: {
      'words|10': [{query: 'Under one'.display_query: 'Under the Man 565'}]}})return res.json(data)
})


module.exports = router

Copy the code

  1. Accessing mock interface data
"scripts": {
    "mock": "nodemon ./mock/server.js",},Copy the code

We add a mock script command under the scripts, perform yarn mock can open a mock services, such as access to the above interface at http://localhost:3001/api/mock

The article finally

The author of this article is Jian Kerry, senior front end engineer. If you think this article is helpful to you, remember to like three even oh, can also scan code to pay attention to my newly established front-end technology public number [have you front end], after all my articles will be synchronized to the public number above. In addition, I built a can help us programmers to take off the single public number, every week will push a few excellent single little sister, if you are a programmer technology is good and just single, then you can scan the following code concern [cause come you are a program ape] public number to open your single journey.