从0到1搭建react工程一(基础环境与devServer服务配置)

主要技术栈

构建工具:webpack v4.x
编译工具:babel v7.x
Js框架:Reactjs v16.8.x
UI库:antd v3.x

初始化工程

目录结构

react-project
/root
  package.json ------------------------- 项目配置信息
  webpack.config.js--------------------- 构建配置文件
  .babelrc ----------------------------- js编译配置文件
  index.html --------------------------- html
    /src ------------------------------- 源代码
      index.js ------------------------ 
// 初始化package.json
yarn init -y

依赖环境

// 安装react,react-dom
yarn add react react-dom antd

dependencies

  • react
  • react-dom
  • antd
// 安装dev环境依赖
yarn add webpack webpakc-cli ... --dev

devDependencies

  • webpack
  • webpack-cli
  • webpack-dev-server
  • @babel/core
  • @babel/preset-env
  • @babel/preset-react
  • babel-loader

package.json中新增scripts字段,并写入start指令以webpack-dev-server启动工程,若不配置构建文件,默认以根目录下webpck.config.js || webpackfile.js为启动配置。即webpack-dev-server === webpack-dev-server --config webpack.config.js || webpackfile.js

最终的package.json文件

{
  "name": "react-project",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server --config webpack.config.js"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "@babel/core": "^7.4.0",
    "@babel/preset-env": "^7.4.2",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  }
}

构建配置

// webpack.config.js
const path = require('path');
const resolve = (dir) => path.resolve(__dirname, dir);

module.exports = {
  entry: './src/index.js',
  output: {
    path: resolve('dist'),
    filename: 'bundle.js',
  },
  resolve: {
    extensions: ['.js', '.jsx'], // import文件时不添加.js .jsx扩展名也可识别
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      }
    ]
  }
}

编译配置

// .babelrc
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
  ]
}

试用React编写代码

index.js

import React from 'react';
import ReactDom from 'react-dom';

ReactDom.render(<div>Hello World</div>, document.getElementById('app'));

启动项目

yarn start

命令行输入yarn start并访问http://localhost:80

成功启动后效果如下图:
从0到1搭建react工程一(基础环境与devServer服务配置)_第1张图片

你可能感兴趣的:(react)