javascriptjquerynode.jswebpackmodular-design

Webpack throws a weird syntax error in JS file


I have a simple file structure for my JS files:

bundle.js
src
 |
 -- main.js
 -- forms
       |
       -- forms.js

My main.js file looks like this:

let forms = require('./forms/forms');

And the forms.js files looks like this:

export default class Forms {
    test = () => {
        alert('Forms.test() executed!');
    }
}

var forms = new Forms();
forms.test();

This throws the following error:

Hash: a1ed74e596de181cec27
Version: webpack 1.14.0
Time: 21592ms
                Asset    Size  Chunks             Chunk Names
./static/js/bundle.js  277 kB       0  [emitted]  main
+ 3 hidden modules

ERROR in ./static/js/src/forms/forms.js
Module build failed: SyntaxError: Unexpected token (4:6)

  2 | 
  3 | export default class Forms {
> 4 |   test = () => {
    |        ^
  5 |       alert('Forms.test() executed!');
  6 |   }
  7 | }

 @ ./static/js/src/main.js 4:12-36

It's giving a syntax error about the line where the test() method is defined. I have added the babel-loader and in the main.js file, ES6 code is transpiled and executed correctly.

My webpack.config.js file looks like this:

module.exports = {
  entry: './static/js/src/main.js',
  output: {
    filename: './static/js/bundle.js'
  },
  watch: true,
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
      }
    ],
  }
};

Does the babel-loader not correctly work on the forms.js file or something? I haven't excluded the file or its folder in the config file or anything, so why the syntax error? I know this is valid JS as I've written it in a different project and it worked fine.

Btw, import in the main.js file doesn't work either, while other ES6 features do work? Does that have anything to do with this?


Solution

  • ES Class Fields & Static Properties is not part of ECMASCRECMAScript 2015 / 2016 but a stage 2 proposition.

    To use it you need to configure babel to include the Class properties transform.

    You can npm install just the Class properties transform plugin in your babel-loader query:

    query: {
      presets: ['es2015'],
      plugins: ['transform-class-properties']
    }
    

    Or npm install the stage 2 preset and include it as a preset in your babel-loader query:

    query: {
      presets: ['es2015', 'stage-2']
    }