Give a file in the public folder the power to read env variables during build like index.html does

Viewed 1103

EDIT:

  1. I already have environment variables configured in this vue-cli . project. But I can't use them in a file inside public.

  2. Basically, what i want is give the same power that the index file already have to another file inside public folder. Access environment variables during build.

I have a .js file in my app that I want to be able to use an environment variable inside. but I didn't find a method of how to add static files to a public folder of the project and Vue still processes these files.

my file:

var iframeOrigin = 'https://example.com';
var iframeProjectFolder = `${iframeOrigin}/chatbot-aliansce-web`;
var iframeEndPoint = `${iframeProjectFolder}/index.html`;

// var iframeOrigin = 'http://localhost:8080';
// var iframeProjectFolder = `${iframeOrigin}`;
// var iframeEndPoint = `${iframeProjectFolder}/index.html`;

I don't want to modify him every time I deploy in production.

3 Answers

This is XY problem. Vue CLI makes NODE_ENV, BASE_URL and VUE_APP_* available at compilation time through process.env, while process is undefined at runtime. If a file needs to be processed, it should be located in src rather than public, then it can make use of environment variables. Depending on how it's supposed to work with the rest of the application, the script could be separate entry point or a part of main appication.

A workaround is to expose compilation-time environment variables to global scope in the application, so they would be accessible outside:

window.appIframeOrigin = process.env.VUE_APP_IFRAME_ORIGIN;

Public script needs to be evaluated after the application in order for appIframeOrigin to become available.

You can create environment variable using .env file.

Environment Variables

You can specify env variables by placing the following files in your project root:

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

An env file simply contains key=value pairs of environment variables:

FOO=foo
BAR=bar

CONCAT=$FOO$BAR # CONCAT=foobar

For more detailed env parsing rules, please refer to the documentation of dotenv.

https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

You can install dotenv npm package to create env variables and define iframeOrigin in the local env file.

iframeOrigin:'http://localhost:8080';
iframeProjectFolder:`${iframeOrigin}`;
iframeEndPoint:`${iframeProjectFolder}/index.html`;

Now use these values using process.env.iframeOrigin, process.env.iframeProjectFolder, process.env.iframeEndPoint

Related