Phil
Phil

Reputation: 1662

Unexpected Token @ when using babel decorator

I am currently building a react project and have started incorporating redux using connect. I am using decorators to reference this i.e.

const mapStateToProps = (state) => {
    return {
        active: state.sortOrder
    }
};

@connect(mapStateToProps)
export default class SortFilter extends Component {
    //component code here
}

SyntaxError: /Sort.js: Unexpected token (10:0) @connect(mapStateToProps)

THis is my webpack config which I have included the babel-transform-decorators and stage-0 preset (as this seemed to be a solution for others).

const PATH = require('path');

const webpack = require("webpack");

const ROOT = '../../../';

const APP_FOLDER = PATH.resolve(__dirname, ROOT, 'app/');
const APP_ENTRY_FILE = PATH.resolve(__dirname, ROOT, APP_FOLDER, 'client.js');

const BUILD_FOLDER = PATH.resolve(__dirname, ROOT, 'app/public/js/');
const PUBLIC_PATH = '/js/';

const BUILD_FILE = 'app.js';

const ESLINT_CONFIG_FILE = PATH.resolve(__dirname, ROOT, 'tools/build/config/eslint-config.json');

var webpackConfig = {
entry: {
    app: APP_ENTRY_FILE
},
output: {
    path: BUILD_FOLDER,
    publicPath: PUBLIC_PATH,
    filename: BUILD_FILE
},
devtool: 'inline-source-map',
debug: true,    
bail: true,
eslint: {
    configFile: ESLINT_CONFIG_FILE
},
module: {
    preLoaders: [
        {
            test: /\.js$/,
            include: [
                APP_FOLDER
            ],
            loader: 'eslint-loader'
        }
    ],
    loaders: [
        {
            test: /\.js$/,
            include: [
                APP_FOLDER
            ],
            loader: 'babel',
            query: {
                compact: false,
                cacheDirectory: true,
                presets: ['es2015', 'react', 'stage-0'],
                plugins: ['transform-decorators-legacy']
            }
        }
    ]        
},
externals: {
    'axios': 'axios',
    'react': 'React',
    'react-router': 'ReactRouter',
    'history': 'History',
    'react-dom': 'ReactDOM'
},
plugins: [
    new webpack.NoErrorsPlugin()
]
};

module.exports = webpackConfig;

Any help in solving this would be much appreciated.

Upvotes: 3

Views: 3771

Answers (2)

Svetlana K
Svetlana K

Reputation: 56

You need to install babel-plugin-transform-decorators:

npm install babel-plugin-transform-decorators-legacy --save-dev

then add in .babelrc:

"plugins": ["transform-decorators-legacy"]

Upvotes: 4

maxgallo
maxgallo

Reputation: 478

Have you tried to move babel configuration in a .babelrc file in the root of the project (removing the babel configuration on webpack) ?

This is how the file looks like:

{
    "presets": [ "es2015", "react" ],
    "plugins": [
        "transform-decorators-legacy"
    ]
}

Upvotes: 1

Related Questions