react安装及简单使用
一、脚手架工具create-react-app安装
使用以下命令进行安装:
create-react-app todolist
- 当项目创建完成后,可以进入项目,并启动:
import React, { Component } from 'react';
/**
import {Component} from 'react'
相当于:
import {Component} from React // 因为react导出React对象
由于解构赋值的原因,所以Component等于React.Component
*/
//所有的组件都要继承Component
class App extends Component {
// 发送页面内容
render() {
return (
>
Hello World
>
);
}
}
// 导出App模块
export default App;
- index.js
lang="en">
>
charset="utf-8">
name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
name="theme-color" content="#000000">
rel="manifest" href="%PUBLIC_URL%/manifest.json">
rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
>TodoList >
>
>
>
id="root">>
>
>
1.快速构建react项目:
-Demo // 项目名
-node_modules // 存放第三方包
-public
-favicon.ico
-index.html
-manifest.json
-src // 页面代码都写在这下面
-App.css
-App.js
-App.test.js
-index.css
-index.js //项目入口
-logo.svg
-serviceWorker.js
-setupTest.js
.gitignore
package.json
README.md
yarn.lock
2.初始化项目
在项目的根目录下打开命令行,输入:
npm i --save react react-dom antd
安装webpack 的三个基本项
npm i -D webpack // 安装最新稳定版
安装webpack 服务器 webpack-dev-server,让启动更方便
npm i --save-dev html-webpack-plugin
清除无用文件 clean-webpack-plugin,将每次打包多余的文件删除
npm i --save-dev style-loader css-loader // css相关loader
npm i --save-dev node-sass sass-loader // scss 相关loader
npm i --save-dev file-loader url-loader // 加载其他文件,比如图片,字体
安装babel
const path = require('path');
const webpack = require('webpack');
const HtmlPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'inline-source-map',
entry: {
index: './src/index.js'
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [{
test: /\.css$/,
loader: ['style-loader', 'css-loader']
}, {
test: /\.scss$/,
loader: ['style-loader', 'css-loader', 'sass-loader']
}, {
test: /\.(png|svg|jpg|gif)$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'img/[name].[hash:7].[ext]'
}
}, {
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
}]
},
devServer: {
contentBase: './build',
port: 8081, // 端口号
inline: true,
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlPlugin({
template: 'public/index.html'
})
]
}
5.在根目录下添加文件 .babelrc,代码如下
"scripts": {
"start": "webpack-dev-server --open --mode production",
"watch": "webpack --watch",
"build": "webpack --mode production",
"dev": "webpack --mode development& webpack-dev-server --open --mode development",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
7.修改public / index.html文件
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
9.修改src / App.js文件
.main {
background: darkgray;
width: 500px;
height: 500px;
margin: 0 auto;
}
11.启动项目
(1) 在项目根目录下执行
yarn start
执行结果:xxx
作者:年轻人多学点
链接:https://www.jianshu.com/p/931b5864a101
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。