在项目中怎么使用react


怎么使用react

  • 在网页中引入react
  • npm下载后在项目中引入react

在网页中引入react

addReact.html


	
		
		
		
	    
	    
	
	
		

上面代码中需要连个地方注意,第一,在最后一个

通过npm 引入到项目

  • 使用React官提供的脚手架用于初始化React项目,使用create-react-app
  • 从头开始创建一个React应用
使用React官方提供的脚手架create-react-app

执行

#安装create-react-app并创建my-app
npm install -g create-react-app
create-react-app my-app
#或者
#npm版本在5.2.0+可以使用npx命令,
npx create-react-app my-app

#进入项目目录,启动项目
cd my-app
npm start
从头开始创建一个React应用
  • 新建一个文件并命名叫demo
  • 在demo文件夹下执行cmd
  • 执行npm init -y (快速建立packge.json)
  • 执行npm install --save react react-dom
  • 在demo文件夹下新建文件夹并命名为src
  • 在src下新建文件并命名index.js
    index.js内容如下
   	import React from "react"
	import ReactDOM from "react-dom"
	const Index = () => {
		return 
Hello React!
} ReactDOM.render(,document.getElementById('index'));
  • 在demo文件夹新新建文件并命名为index.html
    index.html内容如下


	
		
		
		
	
	
		

注意:如果就直接把index.js引入index.html中,会报错,Uncaught SyntaxError: Cannot use import statement outside a module

所以我们还需要webpack对一些语法的转换(es6转换成es5,jsx转换成js)

  • npm install --save-dev webpack webpack-dev-server webpack-cli webpack-merge html-webpack-plugin clean-webpack-plugin babel-loader @babel/preset-react @babel/preset-env @babel/core
  • 在demo文件夹下新建文件webpack.base.conf.js webpack.dev.conf.js webpack.prod.conf.js
    webpack.base.conf.js内容如下
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
module.exports = {
	entry:"./src/index.js",
	output:{
		filename:"bundle.js",
		path:path.resolve(__dirname,"dist")
	},
	module:{
		rules:[
			{
				test:/\.(js|jsx)$/,
				exclude:/node_modules/,
				loader:"babel-loader"
			}
		]
	},
	plugins:[
		new CleanWebpackPlugin(),
		new HtmlWebpackPlugin({
			title:"react",
			template:"./index.html"
		})
	]
}

webpack.dev.conf.js内容如下

const webpack = require("webpack");
const merge = require("webpack-merge");
const path = require("path");
const common = require("./webpack.base.conf.js");
module.exports = merge(common,{
	mode:"development",
	devtool:"inline-source-map",
	plugins:[
		new webpack.HotModuleReplacementPlugin(),
	],
	devServer:{
		contentBase:path.join(__dirname,"dist"),
		port:9000,
		host:"localhost"
	}
})

webpack.prod.conf.js内容如下

const webpack = require("webpack");
const merge = require("webpack-merge");
const common = require("./webpack.base.conf.js");
module.exports = merge(common,{
	mode:"production",
	devtool: 'source-map'
})

  • 执行npm run dev 即可