Webpack使用教程五(Babel)

來源:互聯網
上載者:User

標籤:

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模組

安裝babelnpm install babel-core babel-loader babel-preset-es2015 babel-preset-react安裝reactnpm install react react-dom安裝json loadernpm install json-loader

2、代碼檔案

//Greeter.jsimport React, {Component} from ‘react‘import config from ‘./config.json‘class Greeter extends Component {    render() {        return (            <div>{config.greetText}</div>        );    }}export default Greeter//main.jsimport 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檔案就可以了。源碼下載。

Webpack使用教程五(Babel)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.