Unexpected Vue error causing disruptions in production

While running my website locally with yarn serve, everything works flawlessly.
However, when I attempt to run yarn build and then open the production version locally (using an Nginx server), I encounter an error when trying to access a specific globally-registered component through Vue Router:

TypeError: undefined is not a function

After some troubleshooting, it appears there might be an issue with how components are being globally registered.
It's worth noting that I also have a non-global component that opens without any problems.

This is how I'm currently registering the components:

function registerComponentsGlobally() {
  const requireComponent = require.context("./components/products", false, /\.vue/);
  const keys = requireComponent.keys();
  for (let i = 0; i < keys.length; i++) {
    const fileName = keys[i];
    const componentConfig = requireComponent(fileName);
    const componentName = fileName.split("/").pop().replace(/\.\w+$/, "");
    Vue.component(componentName, componentConfig.default || componentConfig);
  }
}

Alternatively, I may be incorrectly registering them in Vue Router:

async function initializeVue() {
  const products = await fetch("products.json").then(data => data.json());

  function toRoutes(routes, {pageUrl, platforms: {0: {isExternal}}}) {
    if (!isExternal) {
      routes.push({
        path: `/${pageUrl}`,
        name: pageUrl,
        component: () => import(`./components/products/${pageUrl}`),
      });
    }
    return routes;
  }

  new Vue({
    router: new Router({
      mode: "history",
      routes: [...defaultRoutes, ...products.reduce(toRoutes, [])],
    }),
    ...

In the Vue Router's History Mode documentation, I integrated the Nginx code into my configuration file, and the assets load correctly indicating no issues there.

What could I be overlooking?
Appreciate any help!

EDIT: Stack trace provided below for reference:

vue-router.esm.js:1921 TypeError: undefined is not a function
    at Array.map (<anonymous>)
    at a (.*$ namespace object:90)
    at component (main.js:27)
    at vue-router.esm.js:1790
    at vue-router.esm.js:1817
    at Array.map (<anonymous>)
    at vue-router.esm.js:1817
    at Array.map (<anonymous>)
    at Rt (vue-router.esm.js:1816)
    at vue-router.esm.js:1752
    at h (vue-router.esm.js:1959)
    at r (vue-router.esm.js:1733)
    at r (vue-router.esm.js:1737)
    at r (vue-router.esm.js:1737)
    at Pt (vue-router.esm.js:1741)
    at e.zt.confirmTransition (vue-router.esm.js:1988)
    at e.zt.transitionTo (vue-router.esm.js:1890)
    at e.replace (vue-router.esm.js:2212)
    at ue.replace (vue-router.esm.js:2585)
    at a.routeToProduct (product-links.vue:44)
    at ne (vue.runtime.esm.js:1854)
    at HTMLButtonElement.n (vue.runtime.esm.js:2179)
    at HTMLButtonElement.Zi.o._wrapper (vue.runtime.esm.js:6911)

Answer №1

After some trial and error, I finally got it to work by making a simple tweak:

function updateRoutes(routes, {url, platforms: {0: {isExternal}}}) {
  if (!isExternal) {
    routes.push({
      path: `/${url}`,
      name: url,
      component: () => import(`./content/${url}`),
    });
  }
  return routes;
}

became:

function updateRoutes(routes, {url, platforms: {0: {isExternal}}}) {
  if (!isExternal) {
    // Saved directory path as a variable
    const dir = `./content`;
    routes.push({
      path: `/${url}`,
      name: url,
      component: () => import(`${dir}/${url}`),
    });
  }
  return routes;
}

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

Interrupting one process and initiating a new one

Trying to create a simple animation using Velocity.js. This animation will transition between two looping states upon clicking an svg. The first state involves horizontal scaling from scaleX(1) to scaleX(2.5) and back to scaleX(1), while maintaining scaleY ...

Exploring nested JSON data to access specific elements

When I use console.log(responseJSON), it prints the following JSON format logs on the screen. However, I am specifically interested in printing only the latlng values. When I attempt to access the latlng data with console.log(responseJSON.markers.latlng) o ...

What are the best practices for incorporating debounce functionality in redux-form?

I have a search input field on my application. const { searchMails } = this.props; searchMails(keyword); To optimize the searching functionality, I decided to incorporate lodash's debounce method as advised in this particular answer on Stack Overflo ...

Content will adjust to the screen size after a specific re-sizing

When the width is under 1024, I want the body of the page to scale to fit the user's screen without a scrollbar. My goal is to adjust the entire body so that it fits within the browser window without a scrollbar when the width is under 1024. I attempt ...

I don't use Angular to execute a function when (load) is triggered

Whenever I try to open the div, the function doesn't seem to work correctly. Sample HTML: <div class="row table-dark table-bordered"> <div class="col-xl-12" (click)="isCollapsed=!isCollapsed;"> Click Me! <ng-container *ngIf= ...

Tips for invoking a JavaScript function within an iframe

I'm looking to add an iframe to my HTML document, but I also need to pass a variable from a JavaScript function that is located on the same page (which retrieves cookie values). <script type=text/JavaScript> var generateLinkerUrl = function(url ...

Am I following the right approach for implementing Dependency Injection in Node.js?

Recently embarking on a new node project, I encountered a dependency injection issue with my fresh module as a Test-Driven Developer. Here's how I resolved the problem using an approach that involves vows for BDD testing and Sinon. The module in ques ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

Conditional logic in the constructor using Javascript may or may not include if

Check out this starting code snippet. function person(name, age, child){ this.name = name; this.age = age; if(this.child == undefined){ this.child = 'default'; }else{ this.child = child; } } var sarah = new pe ...

Issues with the JavaScript "for in" iteration technique

I am working on a website menu that will be created using JavaScript and an array of objects as the foundation: [ {"menuName":"Contact Info","sectionName":"contacts"}, {"menuName":"Facilities","sectionName":"facilities"}, {"menuName":"Locations","se ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

List displaying empty results

Question has been updated with a solution. I have successfully retrieved a JSON feed from . Although the JSON data is appearing in my scope and displaying in my pre tags, it's not populating in my ng-repeat as expected. app.controller('Instagra ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...

Trouble arises when attempting to categorize an array of objects in JavaScript

My array consists of various objects: [{id: 1, name: 'Apple', category: 'Fruit'} {id: 2, name: 'Melon', category: 'Fruit'} {id: 3, name: 'iPhone', category: 'Phone'} {id: 4, name: 'Samsung Ga ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

Guide to obtaining the number of times each value is repeated in an array of objects for all entries using MongoDB aggregation

I have a data structure that looks like this: { "_id" : ObjectId("5c4404906736bd2608e30b5e"), "assets": [ { "name" : "xa", "id" : 1 }, { "name" : "xs", "id" : 2 } ...

"Create an interactive button on your webpage using Javascript

My current HTML code includes a button with the following syntax: <form id="tfnewsearch" method="get" > <input type="text" id="search_query" name="q" size="21" maxlength="120"><input type="button" id="search_button" name="search ...

Steps to generate an excel document from an HTML table and store it in the project folder

I have created an HTML table with loaded data and now I am looking to convert it into an Excel file and save it in the project directory. Below is the HTML Table structure: <table class='tblNemoList' border='1' cellpadding='3 ...

Issues with cascading style sheet navigation designs

Working on this project is new to me and I am encountering a challenge with two issues. My goal is to create a menu display similar to the image shown here: https://i.sstatic.net/FsHq5.png The problem lies in my inability to underline the selected optio ...

Chrome compatibility problem with scroll spy feature in Bootstrap 3

Having trouble with scroll spy for boosters using the body method " data-spy="scroll". It seems to be working for some browsers like Edge and Google Chrome, but after multiple attempts, it still doesn't work for me. Even after asking friends to test i ...