beeftony's avatar

Dynamically accessing environment variables with Laravel Mix

I'm trying to write a small Vue plugin that just returns the env variable content. Similar to PHPs env() method. Context: I need a url in multiple components, obviously I would want to "outsource" this, because it could possibly change in the future. You cannot use process.env inside of the vue components template though because: Property or method "process" is not defined on the instance but referenced during render.

This is what I've tried to far: I call the prototype function in a mounted hook like this: 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

            // variant 1
            return process.env[name]; // undefined

            // variant 2
            return process.env["MIX_VARIABLE"]; *or* return process.env.MIX_VARIABLE;  // "works" but isnt dynamic obviously

            // variant 3-5 with lodash
            return _get(process.env, name); // undefined
            // or
            return _get(process, 'env[' + name + ']'); // undefined
            // or
            return _get(process.env, '[' + name + ']'); // undefined, worth a try lol
            
            // variant 6
            const test = "MIX_VARIABLE"
            return process.env[test]; // again just for the sake of trying
        }
    }
}

export default Env;

I know that usually object[variable] works fine. But somehow it doesnt in this case, maybe it has to do with the fact that the process.env is empty when accessed without a key and the [name] isnt as "direct" as .MIX_VARIABLE would be.

Does this just not work? Ive researched and found some people (e.g. on Stackoverflow) suggesting this type of accessing (process.env[variable]) so I'm not sure. A colleague of mine tried it with VueCLI (VUE_APP_ prefix) and it seems to work for him, so I'm guessing this is a Laravel Mix related issue)

0 likes
0 replies

Please or to participate in this conversation.