1. 默认已经安装了nodejs,并输入:npm init 根据提示输入内容并 创建 package.json
2. 创建项目 reactapp
reactapp
|--app
|--components
|--productBox.jsx
|--main.jsx
|--build
|--index.html
|--bundle.js (该文件是webpack打包后生成的)
|--webpack.config.js
npm install react --save-dev
npm install webpack webpack-dev-server --save-dev
npm install babel-loader babel-core --save-dev
npm install css-loader less-loader style-loader --save-dev
npm install url-loader --save-dev
3. webpack.config.js文件内容如下:
var path = require('path'); module.exports = { entry: ['webpack-dev-server/client?http://localhost:8080', path.resolve(__dirname, './app/main.jsx')], output: { path: path.resolve(__dirname, './build'), filename: 'bundle.js', }, module: { loaders: [{ test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015','react'] } }, { test: /.css$/,
loader: "style-loader!css-loader" }, { test: /.less$/, loader: 'style!css!less' },{ test: /.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' // 这里的 limit=8192 表示用 base64 编码 <= 8K 的图像 }] }, };
4. package.json文件内容如下:
{
"name": "wp211_app",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"dependencies": {
"react": "^15.4.2",
"webpack-dev-server": "^2.3.0"
},
"devDependencies": {
"babel-core": "^6.23.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"css-loader": "^0.26.1",
"less-loader": "^2.2.3",
"react-dom": "^15.4.2",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.3.0"
},
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --devtool eval --progress --colors --content-base build"
},
"author": "",
"license": "ISC"
}
说明: package.json 修改两处地方: "scripts" 处同上,"main" 对应你的index文件。
5. main.jsx 、 productBox.jsx 、 index.html 三文件内容分别如下:
main.jsx:
import React from 'react' import { render } from 'react-dom'; import AppComponent from './components/productBox.jsx'; render(<AppComponent />, document.getElementById('content'));
index.html:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>React Test</title> </head> <body> <div id="content"></div> <script src="http://localhost:8080/webpack-dev-server.js"></script> <script src="./bundle.js"></script> </body> </html>
productBox.jsx:
var React = require('react'); import { render } from 'react-dom'; var ProductBox = React.createClass({ render: function () { return ( <div className="productBox"> Hello World! </div> ); } }); module.exports = ProductBox;
6. 运行测试:
npm run dev
浏览器访问: http://localhost:8080
Hello World!
....
安装完毕!