標籤:
引言
目前React前端架構是今年最火的。而基於React的React Native也迅速發展。React有其獨特的組件化功能與JSX的新文法,協助前端設計有了更好的設計與便捷,而React Native更是擴大了前端的邊界。
說道React,那就不得不說一下Webpack憑藉它非同步載入和可分離打包等優秀的特性,走在取代Grunt和Gulp的路上。而面向未來的ES6,更是支援模組化處理。
下面我就分享一下關於Webpack+React+ES6的環境搭建(通用)【附加發布版】
準備工作
首先需要準備的就是WebStorm以及安裝node.js,這裡我給出自己雲端硬碟上的,親測可用。對應的地址如下:
WebStorm:連結:http://pan.baidu.com/s/1o787Av4 密碼:z176
node.js:連結:https://nodejs.org/en/ 官網
讓我們跑起來
1、建立項目EChartDemo(我這裡後續會使用一些相關的百度繪畫組件,故以此命名,但這裡只做架構構建,暫不引入百度繪畫組件),變更檔-->設定 ES6環境,:
2、添加package.json檔案,輸入npm init檔案自動組建檔案,如下:
{ "name": "react-echart", "version": "1.0.0", "scripts": { "start": "node server.js" }, "description": "React+EChart百度繪圖組件Demo", "main": "index.js", "repository": { "type": "git", "url": "git+https://github.com/JaminHuang/EChartDemo.git" }, "author": "JaminHuang", "license": "ISC", "bugs": { "url": "https://github.com/JaminHuang/EChartDemo/issues" }, "homepage": "https://github.com/JaminHuang/EChartDemo#readme"}View Code
3、組建檔案後,添加server.js(服務入口檔案)、webpack.config.js(設定檔)、webpack.production.config.js(發布版設定檔),再進行修改對應的Scripts,用於修改啟動和發布。
"scripts": { "start": "node server.js", "prod": "webpack --config webpack.production.config.js" }
4、建立入口檔案index.html,以及相關代碼架構,如下所示
|--src |----containers |------index.js 組件處理主檔案 |------root.js 地址跳轉設定檔 |----service |------index.js 服務要求主檔案 |------request.js 服務要求檔案 |----index.js 主入口檔案 |--index.html 頁面入口檔案 |--package.json 項目資訊與安裝設定檔 |--server.js 服務連接埠入口檔案 |--webpack.config.js 設定檔 |--webpack.production.config.js (發布版)設定檔
View Code
5、需要安裝的包,詳情請看package.json,如下:
"dependencies": { "echarts": "^3.2.3", "isomorphic-fetch": "^2.2.1", "lodash": "^4.15.0", "react": "^15.3.1", "react-dom": "^15.3.1", "react-router": "^2.8.0" }, "devDependencies": { "babel-core": "^6.14.0", "babel-loader": "^6.2.5", "babel-polyfill": "^6.13.0", "babel-preset-latest": "^6.14.0", "babel-preset-react": "^6.11.1", "open": "0.0.5", "react-hot-loader": "^1.3.0", "webpack": "^1.13.2", "webpack-dev-server": "^1.15.1" }View Code
6、建立.babelrc(babel設定檔),重要
{ "presets":["react","latest"]}具體內容的添加配置
1、index.html配置
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div id="wrapper"></div><script src="./public/bundle.js" type="text/javascript"></script></body></html>
View Code
2、server.js配置
‘use strict‘;var open = require(‘open‘);var webpack =require(‘webpack‘);var WebpackDevServer = require(‘webpack-dev-server‘);var config = require(‘./webpack.config.js‘);var compiler = webpack(config);var server = new WebpackDevServer(compiler, { publicPath:config.output.publicPath, hot:true, historyApiFallback: true, quiet: false, noInfo: false, filename: "index.js", watchOptions: { aggregateTimeout: 300, poll: 1000 }, headers: {"X-Custom-Header": "yes"}, stats: {colors: true}});server.listen(3010, function (err, result) { if (err)console.log(err); open(‘http://localhost:3010‘);});View Code
3、webpack.config.js配置
‘use strict‘;var path = require(‘path‘);var webpack = require(‘webpack‘);var config = { devtool: ‘source-map‘, entry: { app: [‘webpack-dev-server/client?http://localhost:3010‘, ‘webpack/hot/dev-server‘, ‘./src/index‘] }, output: { path: path.join(__dirname, ‘public‘), publicPath: ‘/public/‘, //chunkFilename: ‘[id].chunk.js‘, filename: "bundle.js" }, module: { loaders: [ {test: /\.js$/, loaders: [‘react-hot‘, ‘babel‘], include: [path.join(__dirname, ‘src‘)]} ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), //new webpack.optimize.CommonsChunkPlugin(‘shared.js‘), new webpack.DefinePlugin({ ‘process.env‘: { ‘DEBUG‘: true } }) ]};module.exports = config;View Code
4、webpack.production.config.js配置
/** * 建立時間:2016年9月19日 10:45:57 * 建立人:JaminHuang * 描述:設定檔(發布版) */‘use strict‘;var path = require(‘path‘);var webpack = require(‘webpack‘);module.exports = { devtool: false, debug: false, stats: { colors: true, reasons: false }, entry: ‘./src/index‘, output: { path: path.join(__dirname, ‘public‘), publicPath: ‘/public/‘, //chunkFilename: ‘[id].chunk.js‘, filename: ‘bundle.js‘ }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.DefinePlugin({ ‘process.env‘: { ‘NODE_ENV‘: JSON.stringify(‘production‘), ‘DEBUG‘: false } }), //new webpack.optimize.CommonsChunkPlugin(‘shared.js‘), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.AggressiveMergingPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ {test: /\.js$/, loader: "babel", exclude: /node_modules/} ] }};View Code
5、src檔案下的主入口檔案配置
‘use strict‘;import React from ‘react‘;import ReactDOM from ‘react-dom‘;import { browserHistory, Router } from ‘react-router‘import routes from ‘./containers/root‘;import ‘babel-polyfill‘;ReactDOM.render(<Router history={browserHistory} routes={routes}/>, document.getElementById(‘wrapper‘));View Code
6、service檔案(請求服務,如果沒有調用其他API介面則不用建立)下的相關配置
6.1 index.js
‘use strict‘;import * as Request from ‘./request‘;export { Request}
6.2 request.js
‘use strict‘;import fetch from ‘isomorphic-fetch‘;const baseUrl = "http://xxx";export function FetchPost(url, data) { return fetch(`${baseUrl}/${url}`, { headers: {"Content-Type": "application/json"}, method: ‘POST‘, body: JSON.stringify(data) }).then(response=> { return response.json(); })}
7、containers檔案(組件包)下的相關配置
7.1 index.js
‘use strict‘;import React,{ Component } from ‘react‘;import { Link } from ‘react-router‘;class Container extends Component { render() { const { children } = this.props; return (<div>{children}這裡是首頁</div>) }}export default Container;View Code
7.2 root.js
‘use strict‘;import Index from ‘./‘;export default { component: Index, path: ‘/‘}View Code後記
至此,所有配置全部都已經完成了,如果想運行查看則只要輸入”npm start“就可以調試查看啦~如果想發布則輸入”npm prod“就行了。
附上Demo原始碼地址:如果感覺可以的話,請給個Star哦~
地址:https://github.com/JaminHuang/EChartDemo
React+Webpack+ES6環境搭建(自訂架構)