【问题标题】:Asynchronous Loading of vue.config.js for Pre-Rendering Meta Data异步加载 vue.config.js 以预渲染元数据
【发布时间】:2020-05-01 12:40:49
【问题描述】:

我正在尝试将一些数据异步加载到我的 Vue.js 应用程序的配置中,以供 Chris Fritz 的 PrerenderSPA webpack 插件使用,但是 - 它似乎没有预渲染任何路由。

当我对这些值进行硬编码时 - 它们被预渲染得很好,但在尝试异步加载 webpackConfiguration 时似乎失败了。

这是我的淡化尝试:

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;

这可以通过以下方式实现吗:

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

exportConfig();

有没有人在构建时实现了 vue.config.js 这样的异步加载?

【问题讨论】:

  • 为什么你不直接抓取 nuxt.js
  • @Ifaruki Yeh - 我愿意,但这是一个遗留项目。
  • 也许我正在关注这个问题,但如果您需要异步加载的数据在您的 webpack 配置中可用,这是受支持的。 Webpack 配置函数可以返回 Promise

标签: javascript vue.js


【解决方案1】:

configureWebpack 选项还不支持 Promises,同时你可以fetch the data before running the build

补充说明:如果某些路由在预渲染过程中从远程 API 获取数据,并且该 API 不支持 CORS,则需要配置 proxy

例子:

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

【讨论】:

  • 你是在建议我在vue.config.js 中做这样的事情吗?如果我在运行npm run serve 时将ts module.exports = (api) => { console.log({ api }); return { productionSourceMap: process.env.NODE_ENV !== 'production', 放入vue.config.js,我会得到js { api: undefined }
  • 我不确定我是否理解你的问题。这是为您的 Vue 应用程序预渲染页面的一种解决方法。所以它是你构建的一部分。在这种情况下,您通常不会运行 npm run serve,而是运行 npm run build
猜你喜欢
  • 2014-09-14
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
相关资源
最近更新 更多