React+Webpack+ES6环境搭建(自定义框架)

Posted JaminHuang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React+Webpack+ES6环境搭建(自定义框架)相关的知识,希望对你有一定的参考价值。

引言

  目前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环境搭建(自定义框架)的主要内容,如果未能解决你的问题,请参考以下文章

react+es6+webpack环境搭建以及项目入门

webpack4从零配置搭建简单的React16开发环境

基于webpack的React项目搭建

webpack+react+babel环境搭建第二步——静态资源

react開發環境搭建

使用 Babel + React + Webpack 搭建 Web 应用