使用babel装饰器时意外的令牌@

时间:2017-04-19 09:46:35

标签: javascript node.js webpack redux babeljs

我目前正在构建一个反应项目,并已开始使用connect合并redux。我正在使用装饰器来引用它,即

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

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

SyntaxError:/Sort.js:意外的令牌(10:0)       @connect(mapStateToProps)

这是我的webpack配置,其中包括babel-transform-decorators和stage-0预设(因为这似乎是其他人的解决方案)。

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;

任何帮助解决这个问题都会非常感激。

2 个答案:

答案 0 :(得分:4)

您需要安装babel-plugin-transform-decorators

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

然后加入.babelrc:

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

答案 1 :(得分:1)

您是否尝试将babel配置移动到项目根目录中的.babelrc文件中(删除webpack上的babel配置)?

这是文件的样子:

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