当前位置:网站首页>[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 {}
边栏推荐
- Processing of ffmpeg wasapi can't activate audio endpoint error
- Google Earth engine - the use of the neighborhood tobands function
- Heap sort summary
- Architecture design of multi live shopping mall
- Digital stopwatch based on Verilog HDL
- 代码覆盖率
- 必会面试题:1.浅拷贝和深拷贝_浅拷贝
- How painful is it to write unit tests? Can you do it
- 把字符串转换成整数与不要二
- 如何创建和管理自定义的配置信息
猜你喜欢

谢振东:公共交通行业数字化转型升级的探索与实践

把字符串转换成整数与不要二

HLS编程入门

Architecture design of multi live shopping mall

凸优化基础知识
Simple message queue implementation nodejs + redis =mq

The new version of SSM video tutorial in shangsilicon valley was released

基于TensorFlow和Keras的卷积神经网络实现猫狗数据集分类实验

多线程&高并发(全网最新:面试题 + 导图 + 笔记)面试手稳心不慌

HTB-Aragog
随机推荐
VGA display based on FPGA
Power consumption of chip
How to create and manage customized configuration information
QT6 with vs Code: compiling source code and basic configuration
激光雷达障碍物检测与追踪实战——cuda版欧式聚类
HLS编程入门
Pointrender parsing
Are you still using system. Currenttimemillis()? Take a look at stopwatch
How painful is it to write unit tests? Can you do it
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?
Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
Shell调试Debug的三种方式
基于Verilog HDL的数字秒表
Development direction and problems of optaplanner
Xiezhendong: Exploration and practice of digital transformation and upgrading of public transport industry
Notes of Teacher Li Hongyi's 2020 in-depth learning series 8
On the problem that the on-board relay cannot be switched on due to insufficient power supply
Go basic notes_ 4_ map
The laneatt code is reproduced and tested with the video collected by yourself
Coding builds an image, inherits the self built basic image, and reports an error unauthorized: invalid credential Please confirm that you have entered the correct user name and password.