Webpack Babel Arrow功能模块构建错误

时间:2019-01-31 01:37:54

标签: webpack ecmascript-6 babel

我正在尝试在我的React代码中运行一些箭头函数,但是尽管添加了babel加载程序以可读格式构建代码,但我的箭头函数的=部分仍收到错误消息。< / p>

export default class CommentForm extends React.Component {
    constructor(props){
        super(props);
        ...
        this.state = {
            value: '',
            flash: '',
            suggestions: [],
        };

        this.onChange = this.onChange.bind(this);
        this.focus = this.focus.bind(this);
    }
    ...
    onChange = (editorState) => {
        this.setState({
            suggestions: ['test']
        });
    }
    ...
}

错误:

ERROR in ./public/components/app/activity-feed/feed/VerticalTimeline/CommentComponents/CommentForm.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (150:13)

webpack.config.js:

module.exports = {
    mode: 'development',
    entry: "./public/index.js",
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
    },
    module: {
        rules: [
            {   
                test: /\.js$/, 
                exclude: /node_modules/, 
                loader: "babel-loader"
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            }
        ]
    },
};

package.json:

  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    ....
  }

1 个答案:

答案 0 :(得分:1)

您正在尝试使用等号定义类属性。这仍然是一个建议,因此无法使用babel开箱即用。您需要的是一个插件。

npm install --save-dev @babel/plugin-proposal-class-properties

//.babelrc
{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

此提案的一个很酷的功能是它创建了有界函数。因此,不再需要在构造函数中使用.bind!您可以详细了解here