当前位置:网站首页>[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 {}
边栏推荐
- Remember the problem of using redisson to step on the pit once
- 2022 最 NB 的 JVM 基础到调优笔记, 吃透阿里 P6 小 case
- Understanding complexity and simple sorting operation
- dpkg : Breaks: libapt-pkg5.0 (< 1.7~b) but 1.6.15 is to be installedE: Broken packages
- Excel文件处理工具类(基于EasyExcel)
- Only by learning these JMeter plug-ins can we design complex performance test scenarios
- Notes of Teacher Li Hongyi's 2020 in-depth learning series 2
- MATLAB basic grammar (II)
- Network Security Learning (V) DHCP
- 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
猜你喜欢

Network Security Learning (II) IP address

ES6 adds -iterator traversal, for..Of loop

Bug summary

JS ------ Chapter 3 JS cycle

Opengauss kernel analysis: query rewriting

2022 the most NB JVM foundation to tuning notes, thoroughly understand Alibaba P6 small case

Go basic notes_ 4_ map

Efficiency increased by 98%! AI weapon behind operation and maintenance inspection of high altitude photovoltaic power station

Development direction and problems of optaplanner

Are you still using system. Currenttimemillis()? Take a look at stopwatch
随机推荐
Upgrade the jdbc driver to version 8.0.28 and connect to the pit record of MySQL
芯片的功耗
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
来自大佬洗礼!2022 头条首发纯手打 MySQL 高级进阶笔记, 吃透 P7 有望
[zero basis] SQL injection for PHP code audit
代码覆盖率
Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
Notes of Teacher Li Hongyi's 2020 in-depth learning series lecture 1
Transmission download list, download file migration machine guide
salesforce零基础学习(一百一十六)workflow -&gt; flow浅谈
QT6 with vs Code: compiling source code and basic configuration
50 places are limited to open | with the news of oceanbase's annual press conference coming!
1、 MFC introduction
Solve the problem that JSP cannot use session.getattribute()
Lidar obstacle detection and tracking: CUDA European clustering
ASP. Net core 6.0 data validation based on model validation
JDBC 驱动升级到 Version 8.0.28 连接 MySQL 的踩坑记录
基于FPGA的VGA显示
Network Security Learning (I) virtual machine
痞子衡嵌入式:MCUXpresso IDE下将源码制作成Lib库方法及其与IAR,MDK差异