Webpack使用教程五(Babel)

Babel是一个JavaScript编译和工具平台,使用Babel咱们能够:使用新版本的JavaScript(ES6/ES2015,ES7/ES2016),尽管有些浏览器不能所有支持新特性;使用JavaScript语言扩展,例如React JSX。Babel是一个独立的工具,能够与Webpack一块儿使用。Babel已经模块化并分布在不一样的npm模块中,其中核心的功能能够在babel-core模块中得到。其余的部分根据用户的需求来下载:若是想与webpack一块儿使用,须要安装babel-loader模块;若是想使用ES6特性,须要安装babel-preset-2015;若是想使用React JSX,那么须要安装babel-preset-react。固然还有一些其余的配置模块,这里并无所有列出。接下来咱们看一个简单的React例子(源码下载)。html

一、安装必须的npm模块node

安装babel
npm install babel-core babel-loader babel-preset-es2015 babel-preset-react

安装react
npm install react react-dom

安装json loader
npm install json-loader

二、代码文件react

//Greeter.js
import React, {Component} from 'react'
import config from './config.json'

class Greeter extends Component {
    render() {
        return (
            <div>{config.greetText}</div>
        );
    }
}

export default Greeter

//main.js
import React from 'react';
import {render} from 'react-dom';
import Greeter from './Greeter';

render(<Greeter />, document.getElementById('root'));

三、设置webpack文件webpack

module.exports = {
    devtool: 'eval-source-map',
    entry: __dirname + "/app/main.js",
    output: {
        path: __dirname + "/public",
        filename: "bundle.js"
    },
    module: { loaders: [ { test: /\.json$/, loader: "json" }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] },
    devServer: {
        contentBase: "./public",
        colors: true,
        historyApiFallback: true,
        inline: true
    }
};

运行webpack命令,而后打开index.html文件就能够了。源码下载git

相关文章
相关标签/搜索