Oh no, the dreaded encounter with Gulp, Vue, Webpack, Babel causing an unexpected token import SyntaxError!

I have been struggling all day to make this work, but I haven't had any luck. If someone could provide some insight, it would be greatly appreciated.

My goal is to set up an environment for working with ES6 files and Vue using Webpack.

I have installed all the necessary dependencies and created the following files:

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']);

resources/assets/source/js/app.js

var Vue = require('vue');

import Alert from './components/Alert.vue';

new Vue({

    el: '#app',

    components: { Alert },

    ready() {
        alert('ready');
    }

});

resources/assets/source/js/components/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>

After running gulp, everything is bundled and compiled. However, when I try to run it in the browser, I encounter an error:

Uncaught SyntaxError: Unexpected token import
, pointing to a line within the
resources/assets/source/js/app.js
file.

After spending hours trying to troubleshoot the issue, I am at a loss and would appreciate any assistance. Thank you.

Answer №1

It is recommended to eliminate the query object from your webpack.config.js file and instead, create a .babelrc file to house the necessary configurations.

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

Answer №2

issue with the import has been addressed in the previous comments, but there is another hurdle to overcome.

It appears that .vue files are not written in standard JavaScript syntax. To be able to import them, there is a need to convert them into JavaScript.

Upon examining the webpack.config.js, it becomes apparent that files with a .vue extension are not transpiled in any manner.

The solution to this challenge lies in utilizing custom loaders. In this scenario, the appropriate loader to use is vue-loader

Follow these steps to resolve the issue:

  • npm install --save-dev vue-loader
  • After completing the installation, update your webpack.config.js by including the following in the module section:

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

For more information, visit:

Has this provided any assistance? If not, please inform me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging server-sent events (SSE) for real-time updates on a web client using JavaScript

I have been experimenting with server-side events (SSE) in JavaScript and Node.JS to send updates to a web client. To simplify things, I created a function that generates the current time every second: setTimeout(function time() { sendEvent('time&a ...

Can Firebase data be updated in real-time in a Vue app?

Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user. The objective is to seamlessly display the list of friends while refle ...

Encountering npm error code ERR_SOCKET_TIMEOUT while attempting to generate a React application

Every time I attempt to create a React app using the command: npx create-react-app chat-app I encounter this error message: Error I have attempted various solutions in an effort to resolve the error: To check if I am behind a proxy, I ran the following ...

Synchronize the completion of multiple promises in ExpressJs before sending a response

My POST API contains some logic that needs to wait for all promises to finish before sending the response. However, I'm facing an issue with making my server wait using await Promise.all(tasks); I've tried various approaches and even used librar ...

What is the reason for the request to accept */* when the browser is seeking a JavaScript file?

The html source appears as follows: <script type="text/javascript" language="JavaScript" src="myscript.js"></script> Upon debugging the http request using Fiddler, it is evident that the browser (Chrome) sends a GET request for myscript.js wi ...

The dropdown div does not activate when the image is clicked

When the image in the simple dropdown is clicked, it fails to activate the dropdown feature. This issue was encountered while working on a Shopify project, making it challenging to troubleshoot. To demonstrate the problem, I have re-created the scenario i ...

Is there a way to modify an existing job in Kue Node.js after it has been created?

Utilizing Kue, I am generating employment opportunities. jobs.create('myQueue', { 'title':'test', 'job_id': id ,'params': params } ) .delay(milliseconds) .removeOnComplete( true ) ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

Checking validation with parsley.js without triggering form submission

I have been working with the latest release of Parsley for data validation. While it is validating my data correctly, I am encountering an issue where the form does not submit after validation is complete. I have spent hours trying to troubleshoot this pro ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Working with handleChange and onSubmit functions in pure JavaScript without any libraries

Currently developing my initial app, which is a login/register form using JS/Node.js/MySQL. I am facing issues with connecting my form to the database in order to store user data. I haven't utilized "handleChange" or "onSubmit" functions as I am not e ...

Choosing a root element in a hierarchy without affecting the chosen style of a child

I am working on a MUI TreeView component that includes Categories as parents and Articles as children. Whenever I select a child item, it gets styled with a "selected" status. However, when I click on a parent item, the previously selected child loses its ...

How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this: { "network": [ { "name": [ "John", "Jill", "June" ] }, { "town": [ "London", "Paris", "Tokyo" ] }, { "age" : [ "35", "24", "14" ] } ] } Unfortunately, my data is in this format and I have to work w ...

I am encountering challenges with React.js implemented in Typescript

Currently, I'm grappling with a challenge while establishing a design system in ReactJS utilizing TypeScript. The issue at hand pertains to correctly passing and returning types for my components. To address this, here are the steps I've taken so ...

Verifying Session Expiry in Laravel Sanctum and Vue.js

Embarking on a new learning project with Laravel and VueJS, utilizing Sanctum for cookie-based authentication. While I've successfully implemented authentication following various tutorials, none of them address the issue of checking for expired sessi ...

What could be causing the JSON.parse() function to fail in my program?

Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

Utilizing a variable string name for a method in Typescript Vue

My objective is to trigger a different function based on the value of a variable. However, when working in VS Code, I receive an error message that states: 'method' implicitly has a type of 'any' because 'type1Func' and &apos ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...

Can you explain the purpose of the node_modules folder within AngularJS?

While exploring the AngularJS tutorial project, I came across the tutorial with a surprisingly hefty 60-megabyte node_modules directory. Does a simple clientside javascript project truly require such a large amount of unfamiliar data? I decided to delete ...

Get information component from custom instruction

I am looking to apply a style using a directive because I want to verify a value passed to the element. <div v-portrait="photo.portrait"></div> The challenge I'm facing is accessing the data() of my component, but I can't figure out ...