Gulp, Vue, Webpack, Babel和Uncaught SyntaxError:意外的令牌导入

Gulp, Vue, Webpack, Babel and Uncaught SyntaxError: Unexpected token import

本文关键字:意外 令牌 导入 SyntaxError Uncaught Vue Webpack Babel Gulp      更新时间:2023-09-26

我已经试了一整天了,但没有任何运气,所以如果有人能发出一些光,我将非常感激。

我正在尝试使用Webpack设置与ES6文件以及Vue一起工作的环境。

我已经安装了所有依赖项,并创建了以下文件:

webpack.config.js

module.exports = {
    entry: './resources/assets/source/js/app.js',
    output: {
        filename: 'app.js'
    },
    devtool: 'source-map',
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.js'
        }
    },
    module: {
        loaders: [
            {
                test: /'.js$/,
                loader: 'babel',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015']
                }
            },
            {
                test: /'.vue$/,
                loader: 'vue'
            }
        ]
    }
};

gulpfile.js

var gulp       = require('gulp'),
    webpack    = require('webpack-stream');
gulp.task('script', () => {
    "use strict";
    return gulp.src('./resources/assets/source/js/app.js')
               .pipe(webpack(require('./webpack.config.js')))
               .pipe(gulp.dest('./public/assets/js/'));
});
gulp.task('default', ['script']);

资源/资产/资源/js/app.js

var Vue = require('vue');
import Alert from './components/Alert.vue';
new Vue({
    el: '#app',
    components: { Alert },
    ready() {
        alert('ready');
    }
});

资源/资产/资源/js/组件/Alert.vue

<template>
    <div :class="alertClasses" v-show="show">
        <slot></slot>
        <span class="Alert__close" @click="show == false">x</span>
    </div>
</template>
<script>
    export default {
        props: ['type'],
        data() {
            return {
                show: true
            };
        },
        computed: {
            alertClasses() {
                var type = this.type;
                return {
                    'Alert': true,
                    'Alert--Success': type == 'success',
                    'Alert--Error': type == 'error'
                };
            }
        }
    };
</script>

当我运行gulp时,一切都被捆绑和编译,但是当我在浏览器中运行它时,我得到Uncaught SyntaxError: Unexpected token import指向resources/assets/source/js/app.js文件中的行。

经过几个小时的努力找出可能导致它的原因,我已经用尽了想法,正处于放弃的边缘,所以我会感谢任何帮助。

你应该从你的webpack.config.js文件中删除查询对象,并创建一个包含这些内容的.babelrc文件。

{
  "presets": ["es2015"],
  "plugins": ["transform-runtime"],
  "comments": false
}

import问题似乎在上面的评论中得到了解决,但还有一个。

.vue文件似乎不是用标准JavaScript语法编写的。为了导入它们,我们需要以某种方式将它们转换为JavaScript。

在查看webpack.config.js时,您可能会注意到,扩展名为.vue的文件不会以任何方式被编译。

你可以用自定义加载器来解决这个问题。在本例中,您要查找的加载器是vue-loader

解决方法:

  • npm install --save-dev vue-loader
  • 一旦完成,尝试用以下module部分更新webpack.config.js:

module: { loaders: [ { test: /'.js$/, loader: 'babel-loader', query: { presets: ['es2015'] } }, { test: /'.vue$/, loader: 'vue' }, ], }

更多细节:

  • http://vue-loader.vuejs.org/en/index.html

有帮助吗?如果没有,请告诉我。