【问题标题】:Webpack & Babel-Loader - Unexpected Token on Object Rest Operator, with transform-object-rest-spread Plugin InstalledWebpack 和 Babel-Loader - Object Rest Operator 上的意外令牌,安装了 transform-object-rest-spread 插件
【发布时间】:2017-08-18 11:59:04
【问题描述】:

我正在尝试创建一个简单的 VueJS 项目,但无法按照 Vuex 文档中给出的示例说明之一进行操作。我创建了一个 Vuex 模块来封装应用程序的一个模块的状态,如下所示:

export default new Vuex.Store({
    modules: {
        namespaced: true,
        state: {
            created: false,
            // Other variables...
        },
        mutations: {
            CREATE(state) {
                state.app.created = true;
            }
        },
        actions: {
            createCampaign({ commit }) {
                commit('app/CREATE');
            }
        }
    }
});

然后我尝试在我的一个 Vue 组件中使用上面定义的 actions

<template>
    <!-- HTML -->
</template>

<script>
    import { mapActions } from 'vuex';

    let methods = { 
        ...mapActions('app', {
            create: 'createCampaign'
        })
    };

    export default {
        // data, computed...
        methods
    }
</script>

然后它应该被 Webpack 打包并使用 Babel 编译,使用以下配置:

const javascriptRule = {
    test: /\.js$/,
    exclude: /node_modules/,
    use: [{
        loader: 'babel-loader',
        options: {
            presets: ['es2015'],
            plugins: [ 'transform-object-rest-spread' ]
        }
    }]
};

const vueRule = {
    test: /\.vue$/,
    loader: 'vue-loader'
};

module.exports = {
    entry: /* app entry... */,

    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'app.js'
    },

    module: {
        rules: [javascriptRule, vueRule, /* other rules... */]
    },

    // Plugins, other things...
};

但是,当我构建应用程序时,我收到以下错误消息:

Unexpected token:
...mapActions('app', {
^
    create: 'createCampaign'
})

我的 Webpack 配置是否遗漏了什么?我知道扩展运算符最近已从 stage-2 预设中删除,所以我想我会手动将扩展运算符作为插件添加。

提前感谢您的帮助!

【问题讨论】:

  • 你的 vue-loader 配置怎么样?
  • 我已经用 vue-loader 配置更新了我原来的问题。
  • 好的,我建议你把你的 babel 相关的东西从 webpack.config 移动到项目根目录中的 .babelrc 文件中。所以你的 .babelrc 文件应该看起来像这样 { "presets": ["es2015"], "plugins": ["transform-object-rest-spread"] }
  • 看来已经做到了!查看vue-loaderES2015 文档,它声明它将检测BabelJS 的存在并使用它。但是,它没有在 Webpack 配置文件中获取 Babel 配置设置。将它们提取到.babelrc 似乎已经解决了这个问题。谢谢@BelminBedak!
  • 好的,那我把它添加为答案。

标签: webpack vue.js babeljs


【解决方案1】:

您应该将与 Babel 相关的配置从 webpack.config.js 文件移动到项目根目录中的 .babelrc 文件中。

您新创建的.babelrc 文件应如下所示

{
  "presets": ["es2015"],
  "plugins": ["transform-object-rest-spread"]
}

更多信息在这里:https://babeljs.io/docs/usage/babelrc/

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 2018-08-10
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2020-11-16
    • 2016-11-28
    • 2019-03-22
    • 2022-09-29
    相关资源
    最近更新 更多