首页 > 解决方案 > 手动安装 React 应用程序的最佳方法

问题描述

我正在学习 reactjs。我安装了我的反应应用程序

create-react-app first

但我想知道是否有任何手动安装反应应用程序的方法

标签: reactjs

解决方案


我会写最短的教程:)

Step1:创建文件夹和文件结构,如下所示: 在此处输入图像描述

Step2:安装以下依赖项:

npm install -S react react-dom prop-types

第三步:安装开发依赖:

npm install -D babel-core babel-loader babel-plugin-transform-class-properties babel-preset-es2015 babel-preset-react html-webpack-plugin webpack

Step4:将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">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
    <!--Mounting point for React VDOM-->
    <div id="root"></div>
</body>
</html>

Step5 :在根文件夹中创建webpack.config.js文件,内容如下:

 let path = require('path'),
    webpack = require('webpack'),
    HtmlWebPackPlugin = require('html-webpack-plugin')

const PATHS = {
    src: path.join(__dirname, 'src'),
    dist: path.join(__dirname, 'dist'),
    main: path.join(__dirname, 'src/main.js')
}

let wpConfig = {
    entry: PATHS.main,
    output: {
        path: PATHS.dist,
        filename: 'build.js',
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                  "presets": [
                      "es2015",
                      "react"
                   ],
                   "plugins": [
                      "transform-class-properties"
                   ]
                }
            }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({ 
            title: 'My First React App',
            template: './index.html'
        })
    ]
}

module.exports = wpConfig

第六步:添加 nmp 命令。在package.json文件中,转到“脚本”部分并添加如下构建命令:

  "scripts": {
    "build": "node_modules/.bin/webpack"
  }

第7 步:在src文件夹中创建这个简单的 React 应用程序文件(main.js):

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

const App = () => {
    return (
        <div>
            <h1>Hello,</h1>
            <p>This is my first react app!</p>
        </div>
    )
}

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

第八步:运行命令:

npm run build

Webpack 将构建文件(build.jsindex.html)并将其保存到dist文件夹。在浏览器中打开你的/dist/index.html文件,你的第一个从零开始的 react 应用程序就准备好了!从这个基本的应用程序开始,然后添加一些附加功能,如样式表(css、sass)、路由器、webpack 开发服务器、热重载等。快乐的编码!


推荐阅读