欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

react开发环境搭建

程序员文章站 2022-05-31 18:33:10
...

方案一、基于webpack搭建react开发环境

1.mkdir webpack-react && cd webpack-react && npm init

2.在package.json中添加依赖项
"devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/preset-env": "^7.13.9",
    "@babel/preset-react": "^7.12.13",
    "babel-loader": "^8.2.2",
    "html-webpack-plugin": "^4.5.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "webpack": "^4.46.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.2"
  }

3.npm install 在当前项目目录下安装依赖项

4.webpack.config.js 配置webpack

const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    mode:'development',
    devtool:'none',
    entry:'./src/index.js',
    output:{
        filename:'main.js',
        path:path.resolve('dist'),
    },
    devServer:{
        port:3000,
        hot:true,
    },
    module:{
        rules:[
            {
                test:/\.js|jsx$/,
                exclude:/node_modules/,
                use:[
                    {
                        loader:'babel-loader',
                        options:{
                            presets:['@babel/preset-env','@babel/preset-react']
                        }
                    }
                ]
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'./src/index.html'
        })
    ]
}


5.创建src目录,并在src目录中创建index.html,index.js工程文件,
至此基于webpack的react开发环境搭建完成,
在命令行脚手架工具中包含了webpack的配置,不用再单独编写web.config.js文件了。


6.最后执行  npx webpack-dev-server 便可查看执行index.js中的代码.

7.index.js中代码如下:
import React from "react";
import { render } from "react-dom";
//自定义组件
function App(){
    return <div>React</div>
}
render(<App/>,document.getElementById('root'));


8.index.html中的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>


方案二、基于命令行脚手架搭建react开发环境

1.npm i -g create-react-app

2.create-react-app react-app //通过脚手架工具create-react-app 创建react项目react-app