Reputation: 1583
With Nuxt v2 you could access the process environment variables using process.env.npm_package_name
, for example. You still can in Nuxt v3, but it has to be wrapped in a publicRuntimeConfig()
.
This is how I have gone about it:
package.json
{
"name": "nuxt-example-app",
"displayName": "Nuxt v3 Example App",
"version": "0.0.1",
"description": "This is an app primarily to showcase my skills with Nuxt, and other web orientated implementations.",
.
.
.
}
nuxt.config.ts
export default defineNuxtConfig({
publicRuntimeConfig: {
NPM_PACKAGE_NAME: process.env.npm_package_name,
NPM_PACKAGE_DESCRIPTION: process.env.npm_package_description
},
.
.
.
});
app.vue
<script setup lang="ts">
const config = useRuntimeConfig();
useHead({
title: config.NPM_PACKAGE_NAME || '',
meta: [
{ name: 'description', content: config.NPM_PACKAGE_DESCRIPTION || '' }
]
});
</script>
config.NPM_PACKAGE_NAME
is defined, but config.NPM_PACKAGE_DESCRIPTION
is not. process.env.npm_package_description
worked in Nuxt v2, why not now?
The NPM documentation states:
The package.json fields are tacked onto the npm_package_ prefix. So, for instance, if you had
{"name":"foo", "version":"1.2.5"}
in your package.json file, then your package scripts would have thenpm_package_name
environment variable set to "foo", and thenpm_package_version
set to "1.2.5". You can access these variables in your code withprocess.env.npm_package_name
andprocess.env.npm_package_version
, and so on for other fields.
(source)
Running process.env
on the debug console does not even show npm_package_name
in the object, let alone npm_package_description
.
Upvotes: 1
Views: 1286
Reputation: 1583
Not an answer, but an alternative solution that Estus Flask has pointed out, is you can just import the package.json
into nuxt.config.ts
.
nuxt.config.ts
import packageJSON from './package.json';
export default defineNuxtConfig({
app: {
head: {
title: packageJSON.name || '',
charset: 'utf-8',
viewport: 'width=device-width, initial-scale=1',
meta: [
{ name: 'description', content: packageJSON.description || '' }
]
}
},
.
.
.
});
Upvotes: 2