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

Ways to eliminate class from HTML code

Trying to detect if a navigational element has a specific class upon click. If it has the class, remove it; if not, add it. The goal is to display an active state on the dropdown button while the dropdown is open. The active state should be removed when a ...

Storing the values of a React JS application in local storage using

Storing data received from the backend in local storage: async onSubmit(e){ e.preventDefault(); const {login, password } = this.state; const response = await api.post('/login', { login,password }); const user ...

Aligning an element perfectly at the top within a column

I have two columns side by side. The column on the left contains HTML that I cannot control. On the right side, I need to display a comment box that should align with the text clicked on the left hand side. Is it possible to position an element absolutely ...

When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals: var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.` This functions correctly as sh ...

Save a SQL query as a text file using Node.js

I'm having an issue with my code. I am trying to save the results of a SQL query into a text file, but instead of getting the actual results, all I see in the file is the word "object." const fs = require('fs'); const sql = require('mss ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

Utilize the push method to form a new array

var teamMembers = [ ['John D. Adams', '1959-1967', 'Ohio'], ['Dawson Mathis', '1971-1981', 'Georgia'], ]; To generate this dynamically, I am implementing the code below: var data = ne ...

Strategies for resolving the module not found error: Unable to locate '@mui/icons-material/Adb'?

I installed material-ui core using the command below: npm i @material-ui/core However, when running my reactjs code afterwards, I encountered this error message: Module not found: Can't resolve '@mui/icons-material/Adb' Can someone pleas ...

What sets apart posting data through an HTML form submission from posting data through an Ajax request?

Recently, I've encountered an issue with my Post API. When calling it through AJAX, the user parameter is received but the StreamReader returns empty. [HttpPost] [Route("getUserBankList")] public IHttpActionResult getUserBankList(UserProfile ...

Encountered an import error when using "npm run build", but it runs successfully with "npm start"

My React app is running smoothly with npm start, but I encounter an error when trying to build it using npm run build. The error message I receive is: `Creating an optimized production build... Failed to compile. Attempted import error: './parseq-lan ...

While observing a camera in motion, the particles tinted by texture display sporadic flickering on WebGL and Three.js

Check out this jsfiddle I created to illustrate an issue with particles "flickering" when colored using a texture and the camera is moving. Update: The problem occurs even when there is no animation or movement on the particles. If you notice flickering o ...

The 'click' event is not triggering after adding elements to the DOM using AJAX

$(".btn-close").on('click', function () { alert('click'); var win = $(this).closest("div.window"); var winID = win.attr("id"); $(win).find("*").each(function () { var timerid = $(this).attr("data-timer-id"); ...

Leveraging prop data to create dynamic router links in Vue

I am attempting to develop a feature that will dynamically update links on ion buttons depending on the props received. So far, I have: <template> <ion-button router-link :to "`$/+ {{subLink1}}" shape="round">{{linkName1}}& ...

Exploring the capabilities of Vue JS to dynamically update data and model bindings within form

I need help creating a form that allows users to edit their comments. The challenge is to display the current value of the comment using dynamic data from v-for, while also binding the value to a model for sending it with a patch request. Here is an examp ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

Creating a dropdown button in HTML table cells with JavaScript: A comprehensive guide

I'm attempting to create a drop-down button for two specific columns in my HTML table, but all the rows are being converted into drop-down buttons. I only want the "categorycode" and "categoryname" columns to be drop-down. $(document).ready(functio ...

Revamp your array elements with MongoDB - Substring replacement

Having some difficulty replacing a substring within various documents. Below is an example of one such document: { "images" : [ { "url" : "https://example/1234" }, { "url" : "https://example/afaef" }, { "url" : ...

File or directory does not exist: ENOENT error encountered when attempting to access 'distrowserindex.html'

Upon executing ng deploy --preview, an error is encountered: Error: ENOENT: no such file or directory, open 'dist\index.html' at Object.openSync (fs.js:457:3) at readFileSync (fs.js:359:35) Despite attempting various online tutorial ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...