簡體   English   中英

Webpack錯誤:意外令牌

[英]Webpack error: Unexpected token

朋友們! 我在使用webpack構建時遇到麻煩。 在webpack中,我使用babel 6 ^ +這個預設:

presets: ['es2015', 'stage-1', 'react']

npm啟動后,我捕獲了錯誤:

ERROR in ./src/common/components/layout/Header.js
Module build failed: SyntaxError: C:/Users/Anton/projects/isomorphic-redux-app/src/common/components/layout/Header.js: Unexpected token (13:15)
  11 |   }
  12 |
  13 |   handleToggle = () => this.setState({open: !this.state.open});
     |                ^
  14 |
  15 |   render() {
  16 |     return (

起初我以為我在代碼中有錯誤,我只是從Material-UI文檔中復制/粘貼了它,但是它也壞了。 Header.js文件:

import React, { Component, PropTypes } from 'react';
import LeftNav from 'material-ui/lib/left-nav';
import AppBar from 'material-ui/lib/app-bar';
import RaisedButton from 'material-ui/lib/raised-button';

export default class Header extends Component {

  constructor(props) {
    super(props);
    this.state = {open: false};
  }

  handleToggle = () => this.setState({open: !this.state.open});

  render() {
    return (
      <div>
        <RaisedButton
          label="Controlled LeftNav That Opens From Right"
          onTouchTap={this.handleToggle} />
        <LeftNav width={200} openRight={true} open={this.state.open} >
          <AppBar title="AppBar"/>
        </LeftNav>
      </div>
    );
  }
}

和webpack.config:

var path = require('path');
var webpack = require('webpack');
var merge = require('merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');


var webpackConfig = {
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin()
  ]
};

if (process.env.NODE_ENV === 'production') {

  webpackConfig = merge(webpackConfig,{
    devtool: "source-map",
    entry : [
      './src/client/index.js'
    ],
    resolve: {
      extensions: ["", ".js", ".jsx"]
    },
    module: {
    loaders: [{
    test: /\.js$/,
    loader: 'babel',
    exclude: /node_modules/,
    include: __dirname,
    query: {
      presets: ['es2015', 'stage-1', 'react'],

    }
      },
      { 
        test: /\.jsx$/, 
        loader: 'babel', 
        exclude: /node_modules/,
        include: __dirname,
        query: {
          presets: ['es2015', 'stage-1', 'react'],

        }
      },
      { test: /\.(png|jpg|gif|jpeg)$/, loader: 'url-loader?limit=8192'},
      { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap') }
    ]},
    plugins : [
      new webpack.DefinePlugin({
       'process.env': {
          NODE_ENV: JSON.stringify('production')
        }
      }),
      new ExtractTextPlugin("app.css"),
      new webpack.optimize.UglifyJsPlugin({minimize: true})
    ]  
  });

}else{

  webpackConfig = merge(webpackConfig,{
    devtool: 'inline-source-map',
    module: {
      loaders: [{
    test: /\.js$/,
    loader: 'babel',
    exclude: /node_modules/,
    include: __dirname,
      env: {
        development: {
          plugins: [
            'react-transform'
          ],
          extra: {
            'react-transform': {
              transforms: [{
                transform:  'react-transform-hmr',
                imports: ['react'],
                locals:  ['module']
              },
              {
                transform: 'react-transform-catch-errors',
                imports: ['react','redbox-react' ]
              }
            ]}
          }
        }
      },//
        query: {
//          optional: ['runtime'],
      presets: ['es2015', 'stage-1', 'react'],

    }
  },
  { 
    test: /\.jsx$/, 
    loader: 'babel', 
    exclude: /node_modules/,
    include: __dirname,
    env: {
        development: {
          plugins: [
            'react-transform'
          ],
          extra: {
            'react-transform': {
              transforms: [{
                transform:  'react-transform-hmr',
                imports: ['react'],
                locals:  ['module']
              },
              {
                transform: 'react-transform-catch-errors',
                imports: ['react','redbox-react' ]
              }
            ]}
          }
        }
      },
    query: {
      presets: ['es2015', 'stage-1', 'react'],

    }
  },
  { test: /\.(png|jpg|gif|jpeg)$/, loader: 'url-loader?limit=8192'},
  { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap') }
]},
entry : [
  'webpack-hot-middleware/client',
  './src/client/index.js',
],
resolve: {
  extensions: ["", ".js", ".jsx"]
},
plugins : [
  new webpack.HotModuleReplacementPlugin(),
  new ExtractTextPlugin("app.css")
    ]  
  });

}

module.exports = webpackConfig;

我該如何解決?

您不需要在這里使用arrow函數(並且它是無效的語法),因為您正在定義class方法:

handleToggle = () => this.setState({open: !this.state.open});

嘗試以下方法:

handleToggle() { this.setState({open: !this.state.open}); } 

但是,由於類方法不會自動綁定,因此需要在構造函數中或使用它時將其綁定:

constructor(props) {
    super(props);
    this.state = {open: false};
    this.handleToggle = this.handleToggle.bind(this);
  }

如果您是在render或其他類方法中,則需要在其前面添加const或等效項(使用帶有=賦值時):

render() {
    const handleToggle = () => this.setState({open: !this.state.open});
}

您需要使用Babel階段1來獲取類屬性。

http://babeljs.io/docs/plugins/preset-stage-1/

步驟1:添加依賴項,如下所示:

npm install babel-preset-stage-1 --save

步驟2:更改.babelrc文件,如下所示:

{
  "presets": ["es2015", "react","stage-1"]
}

如果我是正確的,則您正在嘗試使用ES7的特性初始化器。 要解決此問題,您將必須使用Stage-1預設。

更多信息在這里

如果要在類上使用箭頭函數並避免綁定到構造函數 (此位):

this.handleToggle = this.handleToggle.bind(this);

然后,您可以使用babel的transform類屬性。 為此,請在命令行中下載模塊:

npm i --save babel-plugin-transform-class-properties

然后在您的.babelrc中:

{
  "plugins": ["transform-class-properties"]
}

然后,您可以使用清潔器語法並在構造函數中刪除綁定:

handleToggle = () => this.setState({open: !this.state.open});

這應該是在Stage-0或Stage-1預設中,但是我只能通過顯式引用插件來使其工作(如上所述)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM