Acces a VUE_APP variable withing a javascript file (js extension)

We are using VUE_APP variables in our project and we need to use them withing a javascript file (a file with .js extension). But we’re getting errors when we load this javascript file into a vue file.

  • env.development

VUE_APP_MYLIB='mylib'

  • vue.config.js
configureWebpack: {
    resolve: {
        alias: {
            '@MyLib': path.resolve(__dirname, process.env.VUE_APP_MYLIB),
        }
    }
}
  • JS file (services.js)

import lib from '@MyLib';

  • Any VUE file
<script>
import services from '@/services.js';
</script>

And when we launch the application, we have this error:

ERROR  Failed to compile with 1 error                                                                                                     

This dependency was not found:

* @MyLib in ./services.js

To install it, you can run: npm install --save @MyLib

I am assuming you are using Vue CLI – @vue/cli and @vue/cli-service to configure and bundle your project.

About environment variables, the important thing to keep in mind is that environment variables defined via .env files are made available to the actual JavaScript code that will run inside the browser. Webpack is running as a standalone Node.js process. So, here we have two process.env objects. One for the JavaScript code that will run inside the browser context and another process.env for the Webpack’s node.js process.

As said, the Vue CLI makes the environment variables available to the JavaScript code and not to the node.js process that invokes Webpack. So, you simply cannot do this:

{
  configureWebpack: {
    resolve: {
      alias: {
        '@MyLib': path.resolve(__dirname, process.env.VUE_APP_MYLIB),
      }
    }
  }
}

If you want to make VUE_APP_MYLIB available to Webpack configuration, you will have to pass it explicitly if using bash or equivalent shell like:

VUE_APP_MYLIB=mylib npx vue-cli-service serve

Or, if you need to load all variables from some file, then you can use dotenv-cli or similar:

# .env.development is file containing `key=value` pairs
dotenv -e .env.development npx vue-cli-service serve

Leave a Comment