Search code examples
vue.jsvue-cli-3

.env VUE_APP_ variable json?


Starting to use the vue cli 3 and ran into a use-case I can't seem to find an answer for.

How can I set an environment variable via a .env file (ie, .env.development, .env.production, etc) that exposes a JSON object? Additionally, is there a way to load an external files contents into an environment variable (i.e., require)?

Appreciate the assistance!


Solution

  • I came up with a solution to solve my own issue...

    Although the previous answers are viable I didn't want to have to JSON.parse every time I wanted to use the JSON in the environment variable.

    The approach I took was to store in each environment-specific file (i.e., .env-development, .env-production, .env-test) a file path to a file containing the JSON. For example...

    VUE_APP_JSON_FILE=./.env.development.json-data
    

    This file would contain the raw JSON...

    Then in my vue.config.js I used the webpack DefinePlugin to load up the file and make it available via a global variable. For example...

    new webpack.DefinePlugin({
         VUE_APP_JSON: JSON.stringify(process.env.VUE_APP_JSON_FILE)
    })
    

    Defining the new variable will make the json available as an object where throughout my app I can simply reference VUE_APP_JSON.property. This saves me from having to JSON.parse the variable all throughout my app.