当前位置:网站首页>[nuxt 3] (x) runtime configuration
[nuxt 3] (x) runtime configuration
2022-07-24 23:44:00 【choukin】
Only the heart can see the essence of things . What is really important is invisible to the naked eye
Runtime configuration
Nuxt Provides runtime configuration API, Used in application and server routing , You can also modify these configurations through environment variables .
Set runtime configuration
Expose configuration and environment changes to other parts of the application , You need to use nuxt.confg Use... In the document runtimeConfig Configuration item To define the configuration of the runtime
Example :
export default defineNuxtConfig({
runtimeConfig: {
// Set a private key that can only be used on the server
apiSecret: '123',
// public Set in the object key stay The client can also use
public: {
apiBase: '/api'
}
}
})
stay runtimeConfig.public Set up in apiBase, Nuxt This configuration will be added to the payload of each page , We can use both server and browser apiBase.
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
environment variable
You usually use environment variable To set configuration items . .
::alert{type=info} Nuxt CLI Built in right dotenv Support for ,
Except that the environment in the project process has changed , If you set .env file , The configuration items in the file can be automatically merged into process.env in , You can use it in nuxt.confg And other modules .
however , After the project is built You want to modify the environment on the server side , This is the time .env It won't work . for example : You can use terminal commands to set parameters ,DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs ::
The runtime configuration will be automatically replaced with environment variables at runtime . So , You must be there. nuxt.config Set the default value in .
Example :
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: '', // can be overridden by NUXT_API_SECRET environment variable
public: {
apiBase: '', // can be overridden by NUXT_PUBLIC_API_BASE environment variable
}
},
})
Access runtime configuration
Vue application
stay Nuxt Project Vue part , You need to call useRuntimeConfig() To access the configuration of the runtime .
Be careful : The client side and the server side are used in different ways :
On the client side , Only publicIn the key It can be used , And this object is writable and responsive .On the server side , All runtime configurations are accessible , But they are all read-only to avoid context sharing .
<template>
<div>
<div>Check developer console!</div>
</div>
</template>
<script setup>
const config = useRuntimeConfig()
console.log('Runtime config:', config)
if (process.server) {
console.log('API secret:', config.apiSecret)
}
</script>
Safety tips : Do not render the run-time configuration to the page or put it in useState Use in ..
::alert{icon=} useRuntimeConfig Only in setup or Lifecycle hook Use in . ::
plug-in unit
If you want to use environment variables in custom plug-ins , Can be in defineNuxtPlugin Use in a function useRuntimeConfig·
Example :
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
console.log('API base URL:', config.public.apiBase)
});
Server routing
You can also route through the server useRuntimeConfig To access the runtime configuration .
export default async () => {
const result = await $fetch('https://my.api.com/test', {
headers: {
Authorization: `Bearer ${useRuntimeConfig().apiSecret}`
}
})
return result
}
Manually enter the runtime configuration
Nuxt Will pass unjs/untyped Try to configure automatic generation for runtime Typescript Interface .
You can also manually set the property runtime configuration :
declare module '@nuxt/schema' {
interface RuntimeConfig {
apiSecret: string
public: {
apiBase: string
}
}
}
// It is always important to ensure you import/export something when augmenting a type
export {}
边栏推荐
- Go基础笔记_4_map
- Notes of Teacher Li Hongyi's 2020 in-depth learning series 5
- QT | event system qevent
- Zheng Huijuan: Research on application scenarios and evaluation methods of data assets based on the unified market
- Yaml writing rules and comparison between yaml and JSON
- Go basic notes_ 4_ map
- Lidar obstacle detection and tracking: CUDA European clustering
- Xiezhendong: Exploration and practice of digital transformation and upgrading of public transport industry
- BGP related knowledge points
- 1、 MFC introduction
猜你喜欢

价值驱动为商业BP转型提供核心动力——业务场景下的BP实现-商业BP分享

基于Verilog HDL的数字秒表

Notes of Teacher Li Hongyi's 2020 in-depth learning series 8

Be an artistic test / development programmer and slowly change yourself

Notes of Teacher Li Hongyi's 2020 in-depth learning series 2

Can Baidu network disk yundetectservice.exe be disabled and closed

Js----- Chapter 4 array

给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享

Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge

Value driven provides the core driving force for the transformation of commercial BP - BP realization under business scenarios - Commercial BP sharing
随机推荐
Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge
Convex optimization Basics
Js----- Chapter 4 array
QT6 with vs Code: compiling source code and basic configuration
Lidar obstacle detection and tracking: CUDA European clustering
Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
激光雷达障碍物检测与追踪实战——cuda版欧式聚类
Talk about how redis handles requests
SQL result export function. If you click the work order but don't enter it, the interface is always blank and there is no response. What should you do?
Yaml writing rules and comparison between yaml and JSON
Notes of Teacher Li Hongyi's 2020 in-depth learning series 4
Simple message queue implementation nodejs + redis =mq
理财产品可以达到百分之6的,我想要开户买理财产品
With screen and nohup running, there is no need to worry about deep learning code anymore | exiting the terminal will not affect the operation of server program code
Go basic notes_ 4_ map
Three ways of shell debugging and debugging
Entity service is an anti pattern
Understanding complexity and simple sorting operation
Mandatory interview questions: 1. shallow copy and deep copy_ Deep copy
Nvida tensorrt deployment (I)