前提: 已經安裝nodejs和npmjavascript
#全局安裝webpack 自動構建化工具,職能管理項目;webpack-dev-server是開發工具,提供 Hot Module Replacement 功能
# webpack 介紹:http://webpack.github.io/docs/what-is-webpack.htmlcss
npm install -g webpack webpack-dev-server
#在項目文件夾路徑下,初始化npm項目html
npm init
#安裝webpack和webpack-dev-server到項目中java
npm install webpack webpack-dev-server --save-dev
#可選:
#安裝css-loader、 style-loader、 image-loader,能夠在js下加載css樣式文件和圖片(可選) node
(webpack還能夠安裝其餘功能,如code-splitting等)react
npm install css-loader style-loader image-loader --save
#安裝reactJs依賴包(react react-dom)和babel依賴包(轉換jsx-js等)webpack
npm install --save react react-dom babel-preset-react babel-preset-es2015 babel-loader babel-core
#新建webpack.config.js到根目錄下,添加如下內容(loader可選):git
module.exports = { entry: "./index.js", output: { path: __dirname, filename: "bundle.js" }, module: { loaders: [ { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react', }, { test: /\.css$/, loader: 'style-loader!css-loader' },{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' } ] } };
#在package.json下添加腳本github
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "start": "webpack-dev-server --devtool eval --progress --colors --hot", "deploy": "NODE_ENV=production webpack -p", "deploy-windows": "SET NODE_ENV=production & webpack -p ", "validate": "npm ls" }
#添加各個文件到根目錄下
---index.jsweb
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<h1>個人世界</h1>,document.querySelector('#container'));
--index.html
<!DOCTYPE html> <html lang="en"> <head> <title>index</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="container"> </div> <script type="text/javascript" src="bundle.js"></script> </body> </html>
#運行後打開http://127.0.0.1:8080/ 便可以
npm start