使用CDN库方式
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script>
<script src="http://static.runoob.com/assets/react/browser.min.js"></script>
- react.min.js React核心库
- react-dom.min.js 提供DOM相关的功能
- browser.min.js 用于将JSX语法转为javascript语法
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Document</title> <script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script> <script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script> <script src="http://static.runoob.com/assets/react/browser.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> ReactDOM.render( <h1>hello world</h1>,document.getElementById('app') ); </script> </body> </html>
使用脚手架方式
我们使用webpack作为脚手架
首先新建目录test,进入test目录
安装webpack
- npm init
- npm install
- npm install webpack
- npm install webpack-dev-server --save-dev
安装react
- npm install react --save
- npm install react-dom --save
安装一些babel插件
- npm install babel
- npm install babel-core
- npm install babel-loader
- npm install babel-preset-react
- npm install babel-preset-es2015
创建一些必须的文件
- touch index.html
- touch App.jsx
- touch main.js
- touch webpack.config.js
配置webpack设置编译器、服务器、载入器
var path = require('path') var webpack = require('webpack') module.exports = { entry: './main.js',output: { path:'./',filename: 'index.js',},devServer: { inline: true,port: 7777 },module: { loaders: [ { test: /\.jsx?$/,exclude: /node_modules/,loader: 'babel-loader',query: { presets: ['es2015','react'] } }] },plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }),new webpack.optimize.UglifyJsPlugin() ] }
根目录新建index.html
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>hello</title> </head> <body> <div id="app"></div> <script src="index.js"></script> </body> </html>
根目录新建mian.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App />,document.getElementById('app'))
根目录新建App.jsx
import React from 'react'; class App extends React.Component { render() { return ( <div> Hello World!!!<br /> 你好世界!!! </div> ); } } export default App;
配置服务
打开package.json 找到scripts节点,插入
"scripts": { "start": "webpack-dev-server --hot","build": "webpack --progress --hide-modules" },
启动服务
npm start