将babel transform-es2015-arrow-functions插件实现到webpack配置

时间:2016-11-04 19:52:16

标签: reactjs webpack ecmascript-6 babeljs

当我向其中一个组件添加ES6箭头功能时,webpack会记录语法错误。我安装了babel-plugin-transform-es2015-arrow-functions,但我不知道如何指示我的webpack构建使用该插件。

如果有人可以查看我的配置文件并告诉我需要包含哪些内容,我们将不胜感激:

webpack.config.js

"use strict";

const debug = process.env.NODE_ENV !== "production";

const webpack = require('webpack');
const path = require('path');

module.exports = {
  devtool: debug ? 'inline-sourcemap' : null,
  entry: path.join(__dirname, 'src', 'app-client.js'),
  devServer: {
    inline: true,
    port: 3333,
    contentBase: "src/static/",
    historyApiFallback: {
      index: '/index-static.html'
    }
  },
  output: {
    path: path.join(__dirname, 'src', 'static', 'js'),
    publicPath: "/js/",
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: path.join(__dirname, 'src'),
      loader: ['babel-loader'],
      query: {
        cacheDirectory: 'babel_cache',
        presets: debug ? ['react', 'es2015', 'react-hmre'] : ['react', 'es2015']
      }
    }]
  },
  plugins: debug ? [] : [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false },
      mangle: true,
      sourcemap: false,
      beautify: false,
      dead_code: true
    }),
  ]
};

此外,是否可以使用一个插件处理所有ES2015变换?你真的需要为每个ES6功能提供一个单独的插件吗?

提前致谢。

更新

这是我的组件无法正确编译:

import React, { Component, PropTypes } from 'react'

class Counter extends Component {

   add = (a + b) => {
      return a + b;
   }


  render() {
    return (
      <p>
         add(6, 9)
      </p>
    )
  }
}

export default Counter

控制台日志:

 Errors while compiling.
client?692d:75 ./src/components/Counter.js
Module build failed: SyntaxError: Unexpected token (5:7)

  3 | class Counter extends Component {
  4 | 
> 5 |    add = (a + b) => {
    |        ^
  6 |       return a + b;
  7 |    }
  8 | 

BabelLoaderError: SyntaxError: Unexpected token (5:7)

  3 | class Counter extends Component {
  4 | 
> 5 |    add = (a + b) => {
    |        ^
  6 |       return a + b;
  7 |    }
  8 | 

0 个答案:

没有答案