Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel + WebPack: class properties can't be compiled

I'm working on simple js app and I ran into a problem related to babel or/and webpack - class (static) properties couldn't be compiled, an error is thrown:

ERROR in ./components/comp1.js
Module parse failed: Unexpected token (2:18)
You may need an appropriate loader to handle this file type.
| export class Comp1 {
|     static states = '123';
| }

I simplified files with this issue, there are two only - entry point index.js:

import { Comp1 } from './components/comp1'
export const components = {
    Comp1
};

and the component looks like:

export class Comp1 {
    static states = {
        first: 1,
        second: 2
    };
}

Most confusing moment is that it compiles successfully on my OSX machine, but won't run on Win 10 PC. I have no idea how OS could affect... I have the following dependencies in package.json:

  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.6.1",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.12"
  }

And webpack.config:

module.exports = function(env) {
    var config = {
        entry: { 'bundle': './index.js' },
        output: {
            filename: '[name].js',
            path: __dirname + '/dist',
            libraryTarget: 'var',
            library: 'ns'
        },
        devtool: 'source-map',
        resolve: { extensions: ['.js', '.json'] },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    include: __dirname + '/components',
                    exclude: /(node_modules|bower_components)/,
                    use: {
                        loader: 'babel-loader'
                    }
                }
            ]
        }
    };

    return config;
};

and .babelrc:

{
  "plugins": [ "transform-class-properties" ],
  "presets": [ "env" ]
}

UPD

I also tried to move babel settings to webpack.config.js, but it doesn't help:

            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env'],
                    plugins: [ "transform-class-properties" ]
                }
            }
like image 711
user1820686 Avatar asked Oct 17 '22 21:10

user1820686


1 Answers

Finally, I found out the cause of the problem - there was a mistake in webpack configuration:

include: __dirname + '/components',

Since my main file index.js in the root folder doesn't match this rule, I guess it leads to the error I described above. So this line with "include" option should be just removed to make everything worked

like image 64
user1820686 Avatar answered Oct 21 '22 00:10

user1820686