前提: 已经安装nodejs和npm
#全局安装webpack 自动构建化工具,职能管理项目;webpack-dev-server是开发工具,提供 Hot Module Replacement 功能
# webpack 介绍:http://webpack.github.io/docs/what-is-webpack.html
npm install -g webpack webpack-dev-server
#在项目文件夹路径下,初始化npm项目
npm init
#安装webpack和webpack-dev-server到项目中
npm install webpack webpack-dev-server --save-dev
#可选:
#安装css-loader、 style-loader、 image-loader,可以在js下加载css样式文件和图片(可选)
(webpack还可以安装其他功能,如code-splitting等)
npm install css-loader style-loader image-loader --save
#安装reactJs依赖包(react react-dom)和babel依赖包(转换jsx-js等)
npm install --save react react-dom babel-preset-react babel-preset-es2015 babel-loader babel-core
#新建webpack.config.js到根目录下,添加以下内容(loader可选):
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下添加脚本
"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.js
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