zoukankan      html  css  js  c++  java
  • 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例子(源码下载)。

    1、安装必须的npm模块

    安装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

    2、代码文件

    //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'));

    3、设置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文件就可以了。源码下载

  • 相关阅读:
    提升树在回归方法中的应用
    前向分布算法
    提升树
    AdaBoost算法学习笔记
    统计学习方法-提升方法
    序列最小最优化算法
    mysql-profiling详解
    mysql,简单介绍一下索引
    MySQL Explain详解
    spring的事务传播行为
  • 原文地址:https://www.cnblogs.com/xfshen/p/5943205.html
Copyright © 2011-2022 走看看