Loading vue.config.js Asynchronously for Pre-Rendering Meta Data

I am facing an issue with asynchronously loading data in my Vue.js application's config for use with Chris Fritz's PrerenderSPA webpack plugin. It seems that the routes are not being pre-rendered as expected.

When I manually input the values, the routes are prerendered successfully. However, when trying to asynchronously load the webpackConfiguration, it fails.

This is a simplified version of my attempt:

const configPromise = new Promise(async (resolve, reject) => {

  // API Fetch for Prismic Routes:
  const blogRoutes = await prismicRoutes;

  let renderRoutes = [
    ...generalRoutes,
    ...blogRoutes,
  ];

  // call `resolve()` with the config object at some point
  resolve({
    pwa: {
      name: 'App',
      themeColor: '#000000',
      msTileColor: '#000000',
      appleMobileWebAppCapable: 'yes',
      appleMobileWebAppStatusBarStyle: 'black',

      workboxPluginMode: 'InjectManifest',
      workboxOptions: {
        swSrc: 'src/service-worker.js'
      }
    },
    configureWebpack: {
      plugins: [
        new PrerenderSPAPlugin({
          staticDir: path.join(__dirname, 'dist'),
          routes: renderRoutes,
        }),
      ],
    },
  });
});

module.exports = configPromise;

Is there a way to achieve this using something like:

async function exportConfig() {
  module.exports = await configPromise;
}

exportConfig();

Has anyone successfully achieved asynchronous loading of the vue.config.js during build time?

Answer №1

Currently, the configureWebpack option does not have support for Promises. In the meantime, it is recommended to fetch the necessary data before initiating the build process.

Additionally: when certain routes require data retrieval from an external API during prerendering, and if the API does not facilitate CORS, setting up a proxy is essential.

For instance:

// build.prerender.js
const prerenderConfig = {
  // ...
  server: {
    proxy: {
      '^/api': {
        target: process.env.API_URL,
        pathRewrite: {
          '^/api' : ''
        }
      }
    }
  }
}

module.exports = (api) => {
  // @api refers to vue-cli api
  api.registerCommand('build:prerender', async (args) => {
    const { routes } = await fetch(...)
    prerenderConfig.routes = routes
    api.chainWebpack(config => {
      config
        .plugin('prerender')
        .use(PrerenderSPAPlugin, [prerenderConfig])
        .end()
    })

    await api.service.run('build', args)
  })
}
     

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

How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file. While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files. The scenario con ...

Is there a way to verify the existence of an Array Field?

For JavaScript, the code would look like this: if (array[x] != undefined && array[x][y] != undefined) { array[x][y] = "foo"; } Is there an equivalent simple method for achieving this in Java? I have tried checking if the field is null or no ...

Communication between Vue parent component and child method

I have a parent and child component setup. I need to call a method in the child component from the parent, wait for a response, and then use that response to add a condition in the parent method. How can this be achieved? <!-- CHILD COMPONENT EXAMPLE ...

JQuery Slider's Hidden Feature: Functioning Perfectly Despite Being Invisible

Having an issue with a jQuery slider on my local HTML page. The sliders are not showing up as intended. I want it to display like this example: http://jsfiddle.net/RwfFH/143/ HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

EJS unable to display template content

I am having an issue with rendering a template that contains the following code block: <% if(type === 'Not Within Specifications'){ %> <% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

AngularJS has encountered an issue with a route resolve promise that has not been completely resolved

I'm currently working on a simple task to manage user roles within routes. The goal is straightforward: Verify the role of the logged-in user on each route (using a resolve function to authenticate the user based on token or login credentials) Direc ...

Can you guide me on how to establish a cookie within a selenium webdriver javascript script?

I am trying to figure out how to set a cookie using a basic webdriver script: WDS.sampleResult.sampleStart(); //WDS.driver.manage().addCookie(new Cookie("connect.sid", "s%3AeexeZcd_-S23Uh30e3Dmd4X9PskWF08s6m5hDurDa5Jj66SupmmiqvKEjAg6HGigl0o0V%2B9R7m4", ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

Utilize JavaScript or Jquery programming to restrict the entry of special characters from the numeric keypad

For the project I'm working on, I need to block users from entering specific characters in a text box: !@#$%^&*(). Can anyone advise me on how to accomplish this using JavaScript/jQuery? The application is built with ASP.NET. ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

Creating responsive arrow heads using D3: A step-by-step guide

Currently, I am working on creating a thermometer-style bar chart using D3.js version 3. While I have successfully created a basic responsive rectangle with two filled colors, I am facing difficulties in figuring out how to add arrow heads to the design. B ...

CSS: Problem Arising from Line Connections Between Tree Elements

I'm currently working on connecting tree nodes with lines in a drawing. I've managed to achieve it to some extent, but there are a few issues like dangling lines that I need to fix. You can find the implementation on codepen here: https://codepe ...

vue-gtag fails to capture any tracking data

I've been working on tracking the visited pages in my Vue.js App, but for some reason it's not functioning correctly. main.ts import VueGtag from 'vue-gtag'; Vue.use(VueGtag, { config: { id: process.env.VUE_APP_GA }, enabled: ...