【问题标题】:...mapState SyntaxError in Vue.js, with vuex... Vue.js 中的 mapState SyntaxError,带有 vuex
【发布时间】:2017-03-27 11:14:29
【问题描述】:

当我在 vue.js 中使用 ...mapState 时,在使用 webpack 捆绑文件时遇到了错误。错误是

模块构建失败:SyntaxError: Unexpected token。

我尝试过各种 babel 插件,例如 stage-0 和 transform-object-rest-spread。

但是,对我来说似乎没有一个可以。请您告诉我如何解决它?

源代码是

<script type="text/babel">

    import { mapState } from 'vuex';


    let [a, b, ...other] = [1,2,3,5,7,9]; // this line is ok

    console.log(a);

    console.log(b);

    console.log(other); 

    export default{

        computed:{

            localComputed(){

                return 10;

            },

            ...mapState({ //this line caused the error

                count: state => state.count

            })

        },

        methods: {
            increment() {
                this.$store.commit('increment');
            },
            decrement() {
                this.$store.commit('decrement');
            }
        }
    }
</script>

这是 webpack 配置片段

{
    test: /\.(js|es|es6|jsx)$/,
    use: [
        {
            loader: 'babel-loader',
            options: {
                presets: [
                    ['react'],
                    ['es2015', {modules: false, loose: true}],
                    ['stage-2']
                ],
                plugins: [
                    ['transform-runtime'],
                    // https://github.com/JeffreyWay/laravel-mix/issues/76
                    ['transform-object-rest-spread'],
                    ['transform-es2015-destructuring']
                ],
                comments: false,
                cacheDirectory: true
            }
        },
        {
            loader: 'eslint-loader',
            options: {
                configFile: eslintConfigPath
            }
        }
    ],
    exclude: excludeReg
}

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    不久前我遇到了类似的问题。据我所知,您的问题是您的 babel-loader 目前不适用于 .vue 文件(这是正确的)。

    处理.vue 文件的vue-loader 在内部也使用babel,但它不会使用webpack 的babel-loader 配置。在 vue-loader 中为 babel 提供配置的最简单方法是(不幸的是)在项目的根文件夹中使用 babel 配置创建一个单独的 .babelrc 文件:

    .babelrc

    {
        presets: [
            ["react"],
            ["es2015", { "modules": false, "loose": true}],
            ["stage-2"]
        ],
        plugins: [
            ["transform-runtime"],
            ["transform-object-rest-spread"],
            ["transform-es2015-destructuring"]
        ]
    }
    

    请注意,.babelrc 需要有效的 JSON。

    【讨论】:

    • 没错,或者你也可以像你提到的那样,直接 'npm i --save babel-preset-stage-2' 并将 ["stage-2"] 添加到 .babelrc 中
    • 是的,您的回答真的很有帮助,非常感谢!最后我将这个 .eslintrc 添加到我的项目的根路径中,这解决了我的问题:{ presets: [ ["react"], ["es2015", { "modules": false, "loose": true}], [ "stage-2"] ],插件:[ ["transform-runtime"] ],cmets: false }
    猜你喜欢
    • 2019-02-23
    • 2020-05-22
    • 2019-09-25
    • 2021-03-05
    • 2018-11-04
    • 2019-05-23
    • 2017-06-06
    • 2019-01-09
    • 2018-01-17
    相关资源
    最近更新 更多