简体   繁体   English

如何在 nuxt.config.js 文件中使用插件的数据?

[英]How to use plugin's data in a nuxt.config.js file?

My plugin, env.js:我的插件 env.js:

export default async (_ctx, inject) => {
  const resp = await fetch('/config.json')
  const result = await resp.json()
  inject('env', result)

  // eslint-disable-next-line no-console
  console.log('env injected', result)

  return result
}

Then an idea was to use it's data inside nuxt.config.js to inject into publicRuntimeConfig:然后一个想法是使用它在nuxt.config.js中的数据注入 publicRuntimeConfig:

import env from './plugins/env.js'

publicRuntimeConfig: {
  test: env,
},

Then in a browser console i'm checking it:然后在浏览器控制台中我正在检查它:

this.$nuxt.$config

It shows me:它向我展示了:

在此处输入图像描述

instead of a value, though this.$nuxt.$env shows the correct values:而不是一个值,尽管this.$nuxt.$env显示了正确的值:

在此处输入图像描述

What's wrong?怎么了?

In nuxt.config.js , your env variable is a JavaScript module , where the default export is the function intended to be automatically run by Nuxt in a plugin's context.nuxt.config.js中,您的env变量是JavaScript 模块,其中默认导出是 function 旨在由 Nuxt 在插件的上下文中自动运行。 Importing the plugin script does not automatically execute that function.导入插件脚本不会自动执行 function。 Even if you manually ran that function, it wouldn't make sense to use an injected prop as a runtime config because the data is already available as an injected prop.即使您手动运行该 function,使用注入的道具作为运行时配置也是没有意义的,因为数据已经作为注入的道具可用。

If you just want to expose config.json as a runtime config instead of an injected prop, move the code from the plugin into an async configuration :如果您只想公开config.json作为运行时配置而不是注入的道具,请将代码从插件移动到异步配置中:

// nuxt.config.js
export default async () => {
  const resp = await fetch('/config.json')
  const config = await resp.json()

  return {
    publicRuntimeConfig: {
      keycloak: config
    }
  }
}

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

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