给百度做网站的公司,长沙餐饮设计公司,山东网站制作定制,网站制作 软件开发有两种方向 通过配置nuxt.config.ts Nuxt提供的钩子函数#xff0c;实现全局变量的获取 runtimeconfig env文件往runtimeconfig放入内容 useAppConfig 通过env文件配置来获取服务端全局变量#xff0c;客户端通过vite.define实现
nuxt.config.ts Nuxt钩子
1. runtim…有两种方向 通过配置nuxt.config.ts Nuxt提供的钩子函数实现全局变量的获取 runtimeconfig env文件往runtimeconfig放入内容 useAppConfig 通过env文件配置来获取服务端全局变量客户端通过vite.define实现
nuxt.config.ts Nuxt钩子
1. runtimeconfig服务端|全局变量
在nuxt.config.ts文件中配置runtimeconfig对象该对象的值只能使用useRuntimeConfig从服务器访问到适合配置一些API秘钥相关的不暴露给前端的数据
但其中runtimeConfig.public和runtimeConfig.app中的值会暴露给前端
export default defineNuxtConfig({runtimeConfig: {apiKey: xxx, // 该值只能在服务端获取// public中的值会暴露给前端public: {baseURL: https://www.blockxu.top,},},
})客户端获取 服务端获取 2. env文件覆盖runtimeConfig中内容
如果在env文件中设置了相同名称NUXT_API_xxx或NUXT_PUBLIC_xxx的变量就会覆盖掉runtimeConfig|runtimeConfig.app|runtimeConfig.public中的变量
NUXT_API_KEY my-api-key
NUXT_PUBLIC_BASE_URL /foo/3. app.config.ts文件配置内容
在根目录创建app.config.ts文件内部的变量可以useAppConfig()获取到
export default defineAppConfig({foo: bar,title: Hello Nuxt,theme: {dark: true,colors: {primary: #ff0000,},},
});const appConfig useAppConfig();
console.log(---appConfig.foo, appConfig.foo); // 输出 barenv文件写入、process.env获取
终端命令中添加--dotenv .env.dev 注如果只写--dotenv .env.dev只能在运行时获取到 dev: nuxt dev --dotenv .env.dev
build: nuxt build --dotenv .env.prod...
VUE_APP_VALUE VALUE123123
VUE_APP_BASEURL https://www.blockxu.top
...运行后在服务器上通过process.env.VUE_APP_VALUE就可以获取到对应的变量
console.log(process.env.VUE_APP_VALUE) // VALUE123123 该方法只能在服务端获取客户端中无法获取到env文件中的内容[UnhandledSchemeError: Reading from “virtual:windi.css” is not handled by plugins (Unhandled scheme).](UnhandledSchemeError: Reading from “virtual:windi.css” is not handled by plugins (Unhandled scheme).) console.log(-----------process.env, process.env); // 客户端 服务端 放入process.env
在执行build后nuxt build --dotenv .env.prod不论在客户端还是服务端都无法获取到process.env
console.log(-----------process);
try {console.log(process);
} catch (error) {console.log(error, error);
}解决办法
通过vite实现
let define {};
// 处理process.env以便在客户端能够取到
Object.keys(process.env).forEach((name) {define[process.env. name] JSON.stringify(process.env[name]);
});export default defineNuxtConfig({vite: {define: {...define,}}
})