代码之家  ›  专栏  ›  技术社区  ›  cphill

Webpack Babel箭头函数模块生成错误

  •  0
  • cphill  · 技术社区  · 6 年前

    我试图在我的反应代码中运行一些arrow函数,但是尽管添加了babel加载器来以可读的格式构建代码,但是我在 = 我的箭头函数的一部分。

    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'],
                }
            ]
        },
    };
    

    包装: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 回复  |  直到 6 年前
        1
  •  1
  •   Alex Michailidis    6 年前

    您正在尝试使用等号定义类属性。这仍然是一个建议,所以它将不会开箱即用的巴别塔。你需要的是一个插件。

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

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

    这个建议的一个很酷的特点是它创建了有界函数。所以不需要使用 .bind 在构造器中!你可以多读一些 here .

    推荐文章