从零构建React项目(一):构建基础框架

2,526 阅读3分钟

1.初始化项目

新建项目文件夹并执行初始化命令

mkdir project_name && cd project_name
yarn init

填写完项目基本信息会生成一个package.json文件。

2.配置react

2.1 安装依赖

yarn add react react-dom react-router-dom

2.2 添加html模板

新建public目录并在目录下添加index.html

<!--public/index.html-->
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title>react-app</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

2.3 添加入口文件

新建src目录并在目录下添加App.js文件和index.js文件

// src/App.js
import React from 'react'

const App = () => (
    <div>build a react + typescript + webpack + dva project </div>
)

export default App
// src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDom.render(
    <App />,
    document.getElementById('root')
)

3 配置webpack

3.1 安装webpack相关要依赖

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

3.2 添加webpack配置

在根目录下创建config文件夹存放webpack相关配置文件,添加以下配置文件:

  • webpack.config.base.js---存放生产环境和开发环境公共的webpack配置
  • webpack.config.dev.js---存放开发环境的webpack配置
  • webpack.config.prod.js---存放生产环境的webpack配置
// config/webpack.config.base.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: path.resolve(__dirname, '../src/index.js'),
    output: {
        filename: '[name].[hash].js', // 打包出的结果文件
        path: path.resolve(__dirname, '../dist') // 打包到dist目录下
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    plugins:[
        new HtmlWebpackPlugin({
            filename: 'index.html', // 打包出来的文件名
            template: path.resolve(__dirname,'../public/index.html'), // 指定模板文件
            hash: true, // 在引用资源的后面增加hash戳
        })
    ]
};
// config/webpack.config.dev.js
const merge = require('webpack-mege')
const baseConfig = require('./webpack.config.base.js')

module.exports = merge(baseConfig, {
    mode:'development'
})
// config/webpack.config.prod.js
const merge = require('webpack-mege')
const baseConfig = require('./webpack.config.base.js')

module.exports = merge(baseConfig, {
    mode:'production'
})

3.3 配置babel

  1. 安装babel依赖
yarn add babel-loader @babel/core @babel/cli @babel/preset-env @babel/preset-react -D
  • babel的核心功能包含在 @babel/core 模块中
  • babel提供的命令行工具@babel/cli,主要是提供babel这个命令
  • @babel/preset-env 主要作用是对我们所使用的并且目标浏览器中缺失的功能进行代码转换和加载 polyfill。在不进行任何配置的情况下,它所包含的插件将支持所有最新的JS特性(ES2015,ES2016等,不包含 stage 阶段),将其转换成ES5代码。
  • core-js和regenerator-runtime可以模拟完整的ES2015+环境。这意味着可以使用诸如Promise和Map之类的新的内置组件、Array.from之类的静态方法、Array.prototype.includes之类的实例方法。
  • @babel/preset-env提供了一个useBuiltIns参数,设置值为usage时,就只会包含代码需要的polyfill。有一点需要注意:配置此参数的值为usage,必须要同时设置corejs。
  1. 创建babel.config.js文件
module.exports = {
  presets: [
    [
      '@babel/env',
      {
        useBuiltIns: 'usage',
        corejs: 3
      }
    ],
    '@babel/preset-react'
  ]
};
  1. webpack中添加module配置
// config/webpack.config.base.js
module.exports = {
  ...
  module: {
      rules: [
        {
          test: /\.(js|ts)x?$/,  //jsx或者tsx文件
          exclude: /(node_modules)/, // 排除node_modules
          use: {
            loader: 'babel-loader'
          }
        }
      ]
  }
}

3.4 配置开发服务器

yarn add webpack-dev-server -D

config/webpack.config.dev.js中添加开发服务配置

...
module.exports = merge(baseConfig, {
    ...
    devServer: {
        port: 3000,
        host: 'localhost',
        contentBase: path.join(__dirname, '../public'),
        watchContentBase: true,
        publicPath: '/',
        compress: true,
        historyApiFallback: true,
        hot: true,
        clientLogLevel: 'error',
        open: true,
        watchOptions: {
          ignored: /node_modules/
        },
    }
})

package.json中添加开发环境运行命令

"scripts": {
    "dev": "./node_modules/.bin/webpack-dev-server --config ./config/webpack.config.dev.js"
}

此时运行yarn dev就可以在浏览器打开http://localhost:3000进行访问了

4 配置TypeScript

4.1 安装依赖

yarn add @types/react @types/react-dom @types/react-router-dom typescript @babel/preset-typescript -D

4.2 修改babel.config.js

module.exports = {
  presets: [
    ...,
    '@babel/preset-typescript'
  ]
};

4.3 根目录下创建tsconfig.json

{
  "compilerOptions": {
    "target": "ES2016",
    "module": "commonjs", 
    "jsx": "react", 
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "inlineSourceMap": true
  },
  "include": [
    "src"
  ]
}

4.4 修改index.jsApp.js文件后缀名为.tsx并修改相关路径,重新运行即可查看