Symfony using Vite with Vue 3 encounters an error: Uncaught ReferenceError - exports is undefined

Currently, I am in the process of developing a Symfony 3 Application with Vite and Vue3 integrated with TypeScript.

To replace Symfony's Webpack Encore, I opted for the Vite Buildtool using this convenient plugin: https://github.com/lhapaipai/vite-bundle

Initially, I followed the migration guide and everything was working smoothly. However, now I seem to be facing an issue where my Vue application is not rendering as expected. Vue Devtools also fail to recognize it. Even when accessing localhost:8000/vue, I am unable to see my components.

The console throws me this error message:

app.js:8 Uncaught ReferenceError: exports is not defined
    at app.js:8:23
(anonymous) @ app.js:8

I'm unsure why this is happening all of a sudden. Could there have been something that I missed during the setup? Below are the details of my configuration files.

In case you're wondering, I don't encounter any errors while running `vite dev / npm run dev`.

This is how my `app.vue` looks like:

<script setup lang="ts">
import BaseLayout from "./layout/BaseLayout.vue";
import StickyBanner from "./patterns/StickyBanner.vue";
import ImageSlider from "./components/image-slider.vue";
import BottomMenu from "./components/bottom-menu.vue";
import NavigationBar from "./components/navigation-bar.vue";
import MasonryGallery from "./components/masonry-gallery.vue";
</script>
<template>
  <BaseLayout>
    <template #header>
      <StickyBanner />
      <NavigationBar />
      <h1>Header</h1>
    </template>
    <template #main>
      <ImageSlider />
      <MasonryGallery />
    </template>
    <template #footer>
      <BottomMenu />
      <h1>Footer</h1>
    </template>
    <slot/>
  </BaseLayout>
</template>
<style lang="scss" scoped></style>

Here's how my `app.ts` file appears:

/*
 * Welcome to your app's main TS file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you import will output into a single css file (app.css in this case)
import './styles/app.css';

// start the Stimulus application
import './bootstrap';
import 'flowbite';

import {createApp} from "vue";
import App from "./vue/App.vue";
import ModeSwitcher from "./vue/patterns/ModeSwitcher.vue";
import ImageSlider from "./vue/components/image-slider.vue";
import StickyBanner from "./vue/patterns/StickyBanner.vue";
import ServiceInfo from "./vue/components/service-info.vue";

const app = createApp({});

app.component('App', App);
app.component('ModeSwitcher', ModeSwitcher);
app.component('ImageSlider', ImageSlider);
app.component('StickyBanner', StickyBanner);
app.component('ServiceInfo', ServiceInfo);

app.mount('#app');

For my vite configuration settings, they look like this in `vite.config.ts`:

import { defineConfig } from "vite";
import symfonyPlugin from "vite-plugin-symfony";
import vue from "@vitejs/plugin-vue";
/* if you're using React */
// import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        /* react(), // if you're using React */
        symfonyPlugin(),
        vue(), // write this
    ],
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm-bundler.js',
        }
    },
    base: '/build/',
    build: {
        outDir: './public/build',
        rollupOptions: {
            input: {
                app: "./assets/app.ts",
                /* you can also provide css files to prevent FOUC */
                styles: "./assets/styles/app.css"
            },
        }
    },
});

This is how my `tsconfig.json` file is configured:

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
}

And finally, here are the contents of my `index.html.twig` file:

{% extends 'base.html.twig' %}

{% block title %}Hello VueController!{% endblock %}

{% block body %}
Test
<div>
    <div id="app">
        <app></app>
    </div>
</div>
{% endblock %}

As for my `base.html.twig` template, it looks like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Welcome!{% endblock %}</title>
    <link rel="icon"
          href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
    {# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
    {% block stylesheets %}
        {{ vite_entry_link_tags('app') }}
    {% endblock %}

    {% block javascripts %}
        {{ vite_entry_script_tags('app') }}
    {% endblock %}
    <script>
        // On page load or when changing themes, best to add inline in `head` to avoid FOUC
        if (localStorage.getItem('color-theme') === 'dark' || (!('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            console.log('dark')
        } else {
            document.documentElement.classList.remove('dark')
            console.log('light')
        }
    </script>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>

Last but not least, here's what my `package.json` contains:

{
  "devDependencies": {
    "autoprefixer": "^10.4.14",
    "core-js": "^3.23.0",
    "postcss": "^8.4.21",
    "postcss-loader": "^7.1.0",
    "regenerator-runtime": "^0.13.9",
    "tailwindcss": "^3.3.1",
    "ts-loader": "^9.4.2",
    "unplugin-vue-components": "^0.24.1",
    "vue": "^3.0",
    "vue-loader": "^17.0.1"
  },
  "license": "UNLICENSED",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "@headlessui/vue": "^1.7.12",
    "@vitejs/plugin-vue": "^4.1.0",
    "flowbite": "^1.6.5",
    "sass": "^1.62.0",
    "vite": "^4.2.1",
    "vite-plugin-symfony": "^0.7.6"
  },
  "type": "module"
}

Answer №1

It is possible that the issue stems from your package.json file.

{
  "module": true
}

Your ESM environment might not be recognizing a variable specific to CommonJS. Have you considered renaming your configuration file to vite.config.cjs? Alternatively, removing "module": true (although this may not be a good idea due to upcoming changes in Vite.js version 5). I recall reading about a similar issue with vite-plugin-symfony in its previous versions - perhaps updating to version 6 could help resolve it?

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

The callback function in jQuery does not function properly in a custom class or object

Hello, I am new to the world of programming so bear with me if this question seems basic. I am currently working on creating a simple wave effect to give the illusion of moving water. Initially, I achieved this using a straightforward jQuery function which ...

Developing modular applications with Vue.js and leveraging locally installed NPM packages

I am currently working on developing a modular application using Vue through the vue-cli-service. The main application and its modules are located in separate folders, with a structure that looks something like this: -- app/package.json /src/** -- mo ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Manually browse through images in photoswipe by clicking on them to move to the previous or next ones

Utilizing photoswipe within my mobile app has been a seamless experience. Instead of utilizing the full screen view, we are displaying images within a target div. A new requirement was introduced to hide the built-in toolbar and incorporate arrow buttons ...

In Internet Explorer 11, the input event in VueJS may not be triggered upon the first input

I am working with an input HTML element that has @input="onInput" assigned to it. Within the onInput method, I have console log output set up, specifically I am logging event.currentTarget.value. However, I've noticed a strange behavior in IE11 - whe ...

Why is my Vue/MySQL Database not showing up online, even though it is accessible locally?

While my application runs smoothly locally, I encounter an issue when deploying to the Heroku server. The page contents linked to the MySQL Database fail to display without any CORS errors or fetch call issues in Chrome Dev Tools. The page loads, but remai ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...

Issue with Material-UI DataGrid Component: Unable to access property 'length' as it is undefined

I need to display my JavaScript Object Data in a table format with pagination and sorting capabilities. I have chosen the DataGrid component from Material UI, but I am encountering some errors. Below is the code snippet: import React from 'react&apos ...

Experiencing difficulties accessing an application hosted on LocalHost without any network interactions?

My team and I are collaborating on an app, and they can log in successfully when running it on their local servers. However, when I try to do the same, I receive an 'Invalid username / password' message without any network activity or console err ...

Success Notification in ASP.net MVC after Form Submission

I am looking to implement a success alert pop-up or message after the form is submitted and action is successful. In this scenario, I want to display "successfully add": Create Action : [HttpPost] [ValidateAntiForgeryToken] public ActionResult Cr ...

The initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...

Implementing a class for a dropdown menu within a JavaScript function

I recently came across a code that I am interested in using on my form to automatically select an option when clicking on a div. $("div").on("click", function(e) { var $select = $("select"); $select.val($(this).data("value")); // simulate cli ...

AJAX request stops functioning once the page is reloaded

As a beginner in JavaScript, I am facing an issue with my AJAX call. I have set up the call to process a back-end function when a button is clicked and expect to receive a response once the function is completed. However, whenever I refresh the page whil ...

Having trouble with a JavaScript Promise that seems to be stuck in limbo

I have developed two custom promises that are quite similar, with the only difference being that they operate on distinct user inputs. Both promises utilize various classes and methods from Google Maps API v-3. What's puzzling is that when the first ...

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

Exploring the benefits of looping with node.js require()

Currently, I have defined the required files as shown below. constantPath = './config/file/' fileAA = require(path.resolve(constantPath + 'A-A')), fileBB = require(path.resolve(constantPath + 'B-B')), fileCC = require(path.r ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

Issue with updating initial state that is null in Redux Toolkit

Encountered an issue while using Redux Toolkit with Redux Persist. Unable to update the initial state of a user if it's null. The code consistently assigns null to the store regardless of passing parameters. import { createSlice, PayloadAction } from ...