Babel预设2015和粗箭头功能的问题

时间:2018-10-05 23:16:59

标签: javascript ecmascript-6 babeljs

当我尝试在类Component内使用粗箭头功能时,出现以下错误...

ERROR in ./src/app/components/Home.js
Module build failed: SyntaxError: C:/myproject/whole/src/app/components/Home.js: Missing class properties transform.

但是,我的package.json中有正确的软件包

对于Babel

"babel-cli": "6.26.0",
"babel-core": "6.26.0",
"babel-loader": "7.1.2",
"babel-preset-env": "1.6.0",
"babel-preset-es2015": "6.24.1",
"babel-preset-es2017": "6.24.1",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "6.24.1",

对于Webpack

"webpack": "3.5.6",
"webpack-dev-server": "2.8.2",
"webpack-merge": "4.1.0",
"webpack-node-externals": "1.6.0"

然后我在Webpack中为Babel设置规则

  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: [
            'react',
            'stage-0',
            ['env', { targets: { browsers: ['last 2 versions'] } }]
          ]
        }
      }
    ]
  }

注意:我还尝试在“反应”之前在此处添加“ es2015”。另外,尝试安装babel-plugin-transform-class-properties,创建.babelrc conf文件,然后在其中添加没有结果的插件。

这是我的组件:

import React, { Component } from 'react';

class Home extends Component {

  consoleHi = () => {
    console.log('Hi');
  };

  render() {
    return (
      <div>
        Hello
        <div>{this.consoleHi()}</div>
      </div>
    );
  }
}

export default Home;

如果我进行转换或使用“常规”功能,则可以使用。

  consoleHi() {
    console.log('Hi');
  }

我想念的是什么? 谢谢,周末愉快。

请记住我正在学习=)

1 个答案:

答案 0 :(得分:1)

尝试安装此插件babel-plugin-transform-class-properties,然后在babel配置中,将transform-class-properties添加到插件数组中,如下所示:

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