React入门:从零搭建一个React项目

一、初始化项目

  1. 新建文件夹,文件名firstreact 文件夹名称不要用react,node这类关键字,后面使用插件时会发生错误。
  2. init项目环境,项目信息可默认或自行修改

    mkdir firstreact
    cd firstreact
    npm init

二、安装webpack

  1. 新建gitignore文件,用于忽略安装的包文件,文件内容: node_modules
  2. 安装webpack, 注意:我此处安装的webpack版本是4.28.4,webpack4和webpack2, webpack3的一些配置不同,具体参考webpack文档webpack中文文档

    npm i --save-dev webpack

三、配置webpack环境

  1. 新建文件夹,文件名:src
  2. src目录下新建文件hello.js,文件内容:

    module.exports = function () {
      var element = document.createElement('h1');
    
      element.innerHTML = 'Hello React';
    
      return element;
    };
  3. src目录下新建文件index.js,文件内容:

    var hello = require('./hello.js');
    
    document.body.appendChild(hello());
  4. 新建文件webpack.config.js,一个最基础的webpack配置如下:

    const webpack = require('webpack');
    const path = require('path');
    var config = { 
        entry: [ './src/index.js' ], // 打包入口文件
        output: {
            path: path.resolve(__dirname, 'dist'), 
            filename: 'bundle.js' 
        } // 打包输出文件
    };
    module.exports = config;
  5. 执行webpack。执行完成后,根目录下会新增一个dist文件夹,文件夹下是打包出来的js文件bundle.js

    webpack
  6. 安装html-webpack-plugin,该插件将为你生成一个 HTML5 文件, 其中包括使用 script 标签的 body 中的所有 webpack 包。

    npm i --save-dev html-webpack-plugin 
  7. html-webpack-plugin配置,webpack.config.js内容如下

    const webpack = require('webpack');
    const path = require('path');
    const HtmlwebpackPlugin = require('html-webpack-plugin');
    
    var config = { 
        entry: [ './src/index.js' ], // 打包入口文件
        output: {
            path: path.resolve(__dirname, 'dist'), 
            filename: 'bundle.js' 
        },// 打包输出文件
        plugins: [
            new HtmlwebpackPlugin({ 
                title: 'Hello React', 
            })
        ]
    };
    
    module.exports = config;
  8. 再次执行webpack,此时dist目录下生成了一个新文件index.html

    webpack
  9. 安装webpack-dev-server和webpack-cli,提供一个简单的 web 服务器,并且能够实时重新加载。

    npm install --save-dev webpack-dev-server webpack-cli
  10. 修改webpack.config

    const webpack = require('webpack');
    const path = require('path');
    const HtmlwebpackPlugin = require('html-webpack-plugin');
    
    var config = {
        entry: [
            'webpack/hot/dev-server',
            'webpack-dev-server/client?http://localhost:3000',
            './src/index.js'
        ], // 入口文件
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        }, // 打包输出文件
        plugins: [
            new HtmlwebpackPlugin({
                title: 'Hello React'
            }),
        ]
    };
    module.exports = config;
  11. 配置webpack启动的快方式,此处webpack4在启动服务是要求设置mode,告知 webpack 使用相应模式的内置优化。未设置会报一个警告。mode选项支持“development”“production”“none”,具体信息请阅文档 修改package.json文件:

    ············
      "scripts": {
        "start": "webpack-dev-server --mode=development --port 3000 --hot",
        "build": "webpack --mode=production"
      }
    ···········
  12. 启动服务,服务启动后打开浏览器访问http://localhost:3000/

    npm run dev
三、优化开发环境
  1. css编译和js编译。现在开发时一般css都会使用扩展css语法,如less或sass,这时就需要在项目中安装css编译插件。此处以less为例。es6和es7语法也需要babel编译。

    const webpack = require('webpack');
    const path = require('path');
    const HtmlwebpackPlugin = require('html-webpack-plugin');
    
    var config = {
        entry: [
            'webpack/hot/dev-server',
            'webpack-dev-server/client?http://localhost:3000',
            './src/index.js'
        ], // 入口文件
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        }, // 打包输出文件
        module: {
            rules: [
                {
                    test: /\.less$/,
                    use: [
                        { loader: 'style-loader' },
                        { loader: 'css-loader' },
                        { loader: 'less-loader' }
                    ]
                },
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: [
                        { loader: 'babel-loader' }
                    ]
                }
            ]
        },
        plugins: [
            new HtmlwebpackPlugin({
                title: 'Hello React'
            }),
        ]
  2. 安装:

    npm i --save-dev less css-loader style-loader less-loader
    npm i --save-dev babel-loader  @babel/core @babel/preset-env @babel/preset-react 

    修改webpack.config.js

    const webpack = require('webpack');
    const path = require('path');
    const HtmlwebpackPlugin = require('html-webpack-plugin');
    
    var config = {
        entry: [
            'webpack/hot/dev-server',
            'webpack-dev-server/client?http://localhost:3000',
            './src/index.js'
        ], // 入口文件
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        }, // 打包输出文件
        module: {
            rules: [
                {
                    test: /\.less$/,
                    use: [
                        { loader: 'style-loader' },
                        { loader: 'css-loader' },
                        { loader: 'less-loader' }
                    ]
                },
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: [
                        { loader: 'babel-loader' }
                    ]
                }
            ]
        },
        plugins: [
            new HtmlwebpackPlugin({
                title: 'Hello React'
            }),
        ]
    };
    module.exports = config;
  3. 根目录下新建.babelrc文件,配置文件内容如下

    {
      "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
      ]
    }
  4. 在src目录下新建文件index.less,文件内容如下

    body{
      h1{
        color: green;
      }
    }
  5. 修改src目录下的index.js文件:

    import hello from './hello.js';
    import './index.less';
    
    document.body.appendChild(hello());
  6. 再次启动服务

    npm run start

目前为止完成了一个最基础的项目结构,后面需要使用其他框架的话再此基础上修改。在这过程中因各个插件工具的版本不同可能会发生不同错误,遇到错误时,请查询相关文档。

四、在项目中使用React

  1. 安装react。

    npm i --save-dev react react-dom
  2. 修改src目录下index.js,文件内容如下:

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    import './index.less';
    
    class APP extends React.Component  {
        render() {
            return (<h1>Hello React</h1>)
        }
    }
    
    ReactDOM.render(<APP/>, document.getElementById('content'));
  3. 在src目录下新建index.html,在html增加挂载节点content。 文件内容如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
      <div id="content"></div>
    </body>
    </html>
    1. 对应修改webpack.config.js文件,为htmlWebpackPlugin修改template
    ············
    
        plugins: [
            new HtmlwebpackPlugin({
                title: 'Hello React',
                template: './src/index.html'
            }),
        ]
        
    ············

目录结构为:

│  .babelrc
│  .gitignore
│  package.json
│  webpack.config.js
│      
└─src
        hello.js
        index.html
        index.js
        index.less
    原文作者:牛什么莹
    原文地址: https://segmentfault.com/a/1190000018216741
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞