Vite shared option 'define' seems to not work as documented on build mode

22 hours ago 3
ARTICLE AD BOX

I have successfully migrated my small app from Vue 2 + Vue-cli to Vue 3 and Vite (8.0.1). There is just one small annoyance I cannot get around. It is related to the Vite shared option 'define'. It seems to not work as documented.

The Issue

Although following the Vite (8.0.1) documentation for the shared option 'define', in env mode this setup is working properly, but in build mode the value is 'undefined'. I assume the defined global is not statically replaced as described in Vite Config.

Here are short extracts from my code.

I my 'package.json' I have the app version specified as

"version": "1.0.0"

In 'vite.config.ts' I have defined a global as

import packageJson from `'./package.json'; define: { __APP_VERSION__: JSON.stringify(packageJson.version), },

In 'vite-env.d.ts' it is declared as

declare const __APP_VERSION__: string;

In my 'ApplicationStore.ts' it is assigned to 'appVersion' as

state: () => ({ ... appVersion: globalThis.__APP_VERSION__, }),

and used in component 'AboutView.vue' like

computed: { ...mapStores(useApplicationStore), appTitle: function () { return 'cDirector v' + this.applicationStore.appVersion; }, },

and in the template as

... <NavBarTitle :title="appTitle" />

Tried Solutions

I have tried to not take the version from 'package.json' and hardcode it in

__APP_VERSION__: JSON.stringify('1.0.0'),

But this is not the solution (same issue).

I also added './package.json' to the include files in 'tsconfig.node.json', but no change as well.

Why is __APP_VERSION__ not statically replaced on build? I have read some of the recommended posts but none does match my issue.

Do I misunderstand the documentation or is there another working approch to the intented feature?

Read Entire Article