I'm currently developing a Vue plugin to retrieve the content of environment variables, similar to PHP's env()
method.
Background: I require a URL in multiple components and have stored it in the .env
file anticipating potential future changes. However, using process.env
directly within component templates results in an error message stating: "Property or method 'process' is not defined on the instance but referenced during render."
This is my current approach: I am invoking the prototype function within a mounted hook like so:
console.log('test: ' + this.env('MIX_COB_PARTNER_URL'));
import _get from "lodash/get";
const Env = {
// eslint-disable-next-line
install(Vue, options) {
Vue.prototype.env = function (name) {
console.log(name); // "MIX_VARIABLE"
console.log(typeof name); // string
// option 1
return process.env[name]; // undefined
// option 2
return process.env["MIX_VARIABLE"]; // constant value, not dynamic
// other options utilizing lodash
return _get(process.env, name); // undefined
// or
return _get(process, 'env[' + name + ']'); // undefined
// or
return _get(process.env, '[' + name + ']'); // undefined
// option 6
const test = "MIX_VARIABLE"
return process.env[test]; // just for experimentation purposes
}
}
}
export default Env;
While typically, object[variable]
syntax functions as expected, in this case it appears that the empty state of process.env
when accessed without a key affects the directness of accessing via [name]
, similar to .MIX_VARIABLE
.
Is this approach ineffective?
Despite encountering suggestions online proposing the use of process.env[variable]
, I remain uncertain.