React项目搭建初始化

162 阅读1分钟

常用库

  • React
  • Redux
  • React-Router
  • next(ssr)
  • typeScript
  • eslint
  • jenkins
  • webpack
  • docker
  • egg.js
  • git(pre-commit, .gitignore)
  • 防抖(debounce) 和 节流(throttle)
  • .babelrc + polyfill
  • 测试(mocha + sinon + enzyme + chai)
  • nodejs(express、koa)
  • nodemon
  • pm2

demo of the github

github.com/Lawguancong… juejin.cn/post/684490…

  • node v14.15.4 ++

初始化项目

mkdir demo-initial
cd demo-initial
yarn init -y

安装webpack

yarn add webpack webpack-cli -D

在webpack.common.js中简单的配置入口(entry)跟输出(output)。

// 在根目录下
mkdir build
cd build
touch webpack.common.js
vim webpack.common.js
const path = require('path');
module.exports={
  entry: path.join(__dirname, '../src/index.js'),
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, '../output')
  },

}

:wq 保存退出

// 在根目录下
mkdir src
cd src
touch index.js
vim index.js
console.log('Hello World');

:wq 保存退出

在package.json中加入一个脚本,

// 在根目录下
vim package.json
// 添加
"scripts": {
    "build": "webpack --config build/webpack.common.js --mode production"
}

:wq 保存退出

Babel

yarn add @babel/core @babel/preset-env @babel/preset-react babel-loader -D
// 在根目录下
vim babel.config.js
// 添加
module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react'
  ],
  plugins: []
}

修改webpack.common.js

// 新增
module: {
  rules: [{
      test: /\.js$/,
      use: ['babel-loader'],
      include: path.join(__dirname, '../src')
  }]
}

React

yarn add react react-dom

修改 src/index.js 中的内容

// 在根目录下
cd src
vim index.js
import React from 'react';
import ReactDom from 'react-dom';

ReactDom.render(<div>Hello React!</div>, document.getElementById('root'));
// 在根目录下
mkdir public
cd public
touch index.html
vim index.html

想要 webpack 能以这个html为模板,还需要一个html-webpack-plugin插件,安装它 html-webpack-plugin 并在webpack.common.js中增加如下配置,这也是用到的第一个插件:

yarn add html-webpack-plugin -D
const HtmlWebpackPlugin = require('html-webpack-plugin');
...
plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'public/index.html',
      inject: true
    })
]

开发环境配置

接下来安装 webpack-dev-server 来启动一个简单的服务器。

yarn add webpack-dev-server -D

修改webpack.common.config.js,增加webpack-dev-server的配置。

devServer: {
  host: 'localhost',
  port: 3000,
  historyApiFallback: true,
  overlay: {
    //当出现编译器错误或警告时,就在网页上显示一层黑色的背景层和错误信息
    errors: true
  },
  inline: true,
  hot: true
}

接下来需要在package.json中增加一个script

"scripts": {
    "dev": "webpack-dev-server --config build/webpack.common.js --mode development --open"
}
yarn dev

便可以在http://localhost:3000 中看到启动的项目。