简体   繁体   English

异步加载 vue.config.js 以预渲染元数据

[英]Asynchronous Loading of vue.config.js for Pre-Rendering Meta Data

I'm attempting to asynchronously load some data in to my Vue.js application's config, to be consumed by Chris Fritz's PrerenderSPA webpack plugin, however - it doesn't seem to be pre-rendering any of the routes.我正在尝试将一些数据异步加载到我的 Vue.js 应用程序的配置中,供 Chris Fritz 的 PrerenderSPA webpack 插件使用,但是 - 它似乎没有预渲染任何路线。

When I hard code the values - they're prerendered fine, it just seems to fail when attempting to async load the webpackConfiguration.当我对这些值进行硬编码时——它们被预渲染得很好,在尝试异步加载 webpackConfiguration 时似乎失败了。

This is my watered down attempt:这是我淡化的尝试:

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

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

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

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

      // configure the workbox plugin
      workboxPluginMode: 'InjectManifest',
      workboxOptions: {
        // swSrc is required in InjectManifest mode.
        swSrc: 'src/service-worker.js',
        // ...other Workbox options...
      }
    },
    configureWebpack: {
      plugins: [
        new PrerenderSPAPlugin({
          staticDir: path.join(__dirname, 'dist'),
          routes: renderRoutes,
        }),
      ],
    },
  });
});

module.exports = configPromise;

Can this be achieved with something like:这可以通过以下方式实现:

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

exportConfig();

Has anyone achieved such an asynchronous loading of the vue.config.js at build time?有没有人在构建时实现了 vue.config.js 的这种异步加载?

The configureWebpack option doesn't support Promises yet, meanwhile you can fetch the data before running the build configureWebpack选项还不支持 Promises,同时您可以在运行构建之前获取数据

Additional note: if some routes fetch data from a remote API while prerendering , and the API does not support CORS, you need to configure a proxy .附加说明:如果某些路由在预渲染时从远程 API 获取数据,并且 API 不支持 CORS,则需要配置代理

Example:例子:

// 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)
  })
}
     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM