一分钟搭建Webpack+react+es6框架
最近react刷屏的厉害,而随着它一起走进我们视野的还有webpack,webpack只是个工具,为什么如此火呢?因为简单好了不废话。
直接进入正题:
打开命令行工具:
npm install -g webpack npm install -g webpack-dev-server mkdir webpack-react-es6 cd webpack-react-es6 npm init # 一直点回车 如果懒得填一些信息
打开package.json 复制以下代码:
{ "name": "react-es6-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "webpack-dev-server --hot --progress --colors", "build": "webpack --progress --colors" }, "author": "", "license": "ISC", "devDependencies": { "babel-core": "^6.7.2", "babel-loader": "^6.2.4", "babel-plugin-react-transform": "^2.0.2", "babel-preset-es2015": "^6.6.0", "babel-preset-react": "^6.5.0", "css-loader": "^0.23.1", "file-loader": "^0.8.5", "html-webpack-plugin": "^2.10.0", "react": "^0.14.7", "react-hot-loader": "^1.3.0", "react-transform-hmr": "^1.0.4", "sass-loader": "^3.2.0", "style-loader": "^0.13.0", "url-loader": "^0.5.7", "webpack": "^1.12.14", "webpack-dev-server": "^1.14.1" } }
创建webpack.config.js,复制以下代码:
var path = require('path'); var webpack = require('webpack'); var ROOT_PATH = path.resolve(__dirname); var APP_PATH = path.resolve(ROOT_PATH, 'app'); var BUILD_PATH = path.resolve(ROOT_PATH, 'build'); // var htmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: [ 'webpack/hot/only-dev-server', "./app/index.js" ], output: { path: BUILD_PATH, filename: "bundle.js" }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", query: { presets:['react','es2015'] } }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'], include: APP_PATH }, { test: /\.(png|jpg)$/, loader: 'url?limit=40000' } ] }, resolve:{ extensions:['','.js','.json'] }, devServer: { hot: true, inline: true }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.HotModuleReplacementPlugin() ] };
根目录下创建index.html,为了调试用:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>New React App</title> </head> <body> <div id="content"></div> <script src="bundle.js"></script> </body> </html>
根目录下创建app文件夹,新建index.js
import React from 'react'; import ReactDOM from 'react-dom'; let App = React.createClass({ render() { return(<h1>Hello, world!</h1>); } }); ReactDOM.render(<App/>, document.getElementById('content'));
最后在根目录下敲命令npm install,安心等待就ok,不过有很大的可能部分模块安装失败,比如node-sass,比较顽固,需要反复安装多次。
如果实在安装不成功,就直接下载http://pan.baidu.com/s/1bnYgWgv。