搭建一个简单的react框架

1,009 阅读3分钟

前言

写一个最新的react简单框架,会维护下去,喜欢的同学可以评论留言,也欢迎技术讨论

项目简介

1.技术栈目前是最新的

node 10.12.0 // or newer
react 16.12.0 
webpack 4.41.2

2.包管理工具

常用的有npm yarn等,本人这里使用npm,使用yarn的小伙伴注意下命令区别

直接开始

初始化项目

先创建一个目录并进入

mkdir react-frame && cd react-frame

初始化项目,填写项目信息(可一路回车)

npm init

安装webpack

npm i webpack webpack-cli webpack-dev-server -D 

npm i react react-dom -S

npm 中 -D和-S两者区别:

npm使用add添加包,-D等于--save-dev  -S等于--save
-D是你开发时候依赖的东西,--S 是你发布之后还依赖的东西

安装好后根目录下放一个webpack基础的开发配置webpack.config.js

echo > webpack.config.js

配置内容

const path = require('path');

module.exports = {
    // 入口
    entry: './src/index.js',
    mode: 'development',
  output: {
    filename: 'bundle.js',
    // 相对于URL的路径,输出文件路径
    /* react The publicPath property is a special property that helps us with our dev-server. It specifies the public URL of the the directory — at least as far as webpack-dev-server will know or care. If this is set incorrectly, you’ll get 404’s as the server won’t be serving your files from the correct location!*/
    publicPath: "/dist/",
    // 输出目录绝对路径
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    contentBase: path.join(__dirname, "public/"),
    port: 3000,
    publicPath: "http://localhost:3000/dist/",
  },
  // extensions 省略后缀
  resolve: { extensions: ["*", ".js", ".jsx"] },
};


配置package.json

{
    ....
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev": "webpack-dev-server --open --hot --port 3001 --host 127.0.0.1"
  },
    ....
}
 

新建需要的文件和文件夹

项目初始化需要的文件

建立文件夹src、public、dist

mkdir src dist public

建立文件src/index.js、public/index.html

cd src && touch index.js && cd ..
cd public && touch index.html && cd ..

dist/index.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">
</head>

<body>
    <div id="root"></div>
    <!-- noscript 元素用来定义在脚本未被执行时的替代内容(文本)。 -->
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <script src="../dist/bundle.js"></script>
</body>

</html>

src/index.js的内容

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

// 利用babel来写jsx 运行的时候会转换成createElement创建
const element = <div>aaaa啊aa</div>;
// 渲染dom元素 指定容器
ReactDOM.render(element, document.getElementById('root'));


启动项目

npm run dev

利用babel启用jsx,react,css等特性

参考webpack官方

参考react官方推荐

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader url-loader style-loader css-loader
const path = require('path');

module.exports = {
  entry: './src/index.js',
  mode: 'development',
  output: {
    filename: 'bundle.js',
    // 相对于URL的路径,输出文件路径

    // react The publicPath property is a special property that helps us with our dev-server. It specifies the public URL of the the directory — at least as far as webpack-dev-server will know or care. If this is set incorrectly, you’ll get 404’s as the server won’t be serving your files from the correct location!
    publicPath: "/dist/",
    // 输出目录绝对路径
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    contentBase: path.join(__dirname, "public/"),
    port: 3000,
    publicPath: "http://localhost:3000/dist/",
  },
  // extensions 省略后缀
  resolve: { extensions: ["*", ".js", ".jsx"] },
  module: {
    rules: [
      {
        /*src目录下面的以.js结尾的文件,要使用babel解析*/
        /*cacheDirectory是用来缓存编译结果,下次编译加速*/
        test: /\.(js|.jsx)$/i,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react'],
          },
        },
      },
      // 
      // The following webpack.config.js can load CSS files,
      // embed small PNG/JPG/GIF/SVG images as well as fonts as Data URLs 
      // and copy larger files to the output directory.
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        loader: 'url-loader',
        options: {
          limit: 8192,
        },
      },
    ],
  },
};

安装sass防止css冲突

安装方式 npm install sass-loader node-sass --save-dev

webpack的 rules下面添加


·····
            {
                test: /\.scss$/i,
                // npm install sass-loader node-sass webpack --save-dev
                use: ['style-loader', 'css-loader', 'sass-loader'],
            },

·····

proxy代理

devServer下有个proxy属性可以设置我们的代理

 devServer: {
       ...
        proxy: { // 配置服务代理
            '/api': {
                 target: 'http://localhost:8000',
                 pathRewrite: {'^/api' : ''},  //可转换
                 changeOrigin:true
            }
        },
        port: 8000 // 端口
    },

复制代码在 localhost:8000 上有后端服务的话,你可以这样启用代理。请求到 /api/users 现在会被代理到请求 http://localhost:8000/users 。(注意这里的第二个属性,它将'/api'替换成了'')。changeOrigin: true可以帮我们解决跨域的问题。

单元测试

请看我另一文章:点这里