I am using Vue + Vite + TS and I am building a few libraries that I would like to build and import somewhere else.
The point is that I set some environment variables using the dotenv, hence I can use things like import.meta.env.MY_VARIABLE.
But they are being availed during the run time of the place I run them, hence the env files need to be placed in the ponent that requires those libs.
I would like to know if there is way so they get replaced in the build time.
I am using Vue + Vite + TS and I am building a few libraries that I would like to build and import somewhere else.
The point is that I set some environment variables using the dotenv, hence I can use things like import.meta.env.MY_VARIABLE.
But they are being availed during the run time of the place I run them, hence the env files need to be placed in the ponent that requires those libs.
I would like to know if there is way so they get replaced in the build time.
Share Improve this question edited Feb 11, 2022 at 15:50 Eduardo Sousa asked Feb 11, 2022 at 15:35 Eduardo SousaEduardo Sousa 1,0751 gold badge12 silver badges28 bronze badges2 Answers
Reset to default 3Maybe you want to use the define option.
let monConfig =
{
plugins: [vue()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url))
},
},
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
nested: resolve(__dirname, 'auth_redirect.html')
}
}
}
}
export default defineConfig(({ mand, mode, ssrBuild }) => {
if (mand === 'serve')
{
//
return monConfig;
}
else
{
monConfig.define = {
"BUILD_TIMESTAMP": new Date().toISOString()
};
// mand === 'build'
return monConfig;
}
})
And then you can just assign BUILD_TIMESTAMP to any javascript variable in your appCode.
const buildNum = "BUILD_TIMESTAMP";//You will get right val in this
.
define has to be patible with https://esbuild.github.io/api/#non-analyzable-imports so gives issues in serve mode. So I have used it conditionally in build mode only. In Dev Mode you will see just raw value of buildNum variable.
Unfortunately, the accepted answer is wrong. First, it will fail on build-time because the date is not correctly formed.
This depends on how you build the app. In all cases, you should expose the env var like this (docs on vite and .env)
VITE_SENTRY_RELEASE_VERSION=something
Let's say you have the build script in the package.json like this
scripts: {
"build": "NODE_ENV=production svelte-kit sync && vite build",
}
and you use pnpm. The mand would be
VITE_SENTRY_RELEASE_VERSION=something pnpm build
Now, in the code, you would reference it like this:
export const sentryRelease = import.meta.env.VITE_SENTRY_RELEASE_VERSION;
The value will be replaced with the correct env variable value.