I
I
Islam Ibakaev2017-05-22 10:46:16
JavaScript
Islam Ibakaev, 2017-05-22 10:46:16

Why can't access the environment variable?

raised the project with a command vue init webpack project-name
figured out how to add pug and stylus
I want to set up environment variables: I used the plugin , created a file .env, added a variable API_SECRET_KEY=efb9erfdf6fd9vfd98vd8ssv(the value of the variable is fictitious for example) and sent it .envto .gitignore
corrected /config/index.js
below what I added to the template configuration

const path = require('path')
const Dotenv = require('dotenv-webpack')

module.exports = {
...
...
...
  module: {
    rules: [
      {
        test: /.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            css: 'stylus-loader'
          }
        }
      }
    ]
  },
  plugins: [
    new Dotenv({ path: path.join(process.cwd(), '.env') })
  ]
}

I'm trying to App.vueoutput a variable to the console, process.env.API_SECRET_KEY,but it gives out undefined
What's the problem? I did everything according to the instructions. How do you get variables from .envin the component's code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2017-06-01
@devellopah

With webpack 2, I solved the issue like this:
Using DefinePlugin, I defined variables in the global scope:

const GLOBALS = {
  'process.env': {
    'NODE_ENV': JSON.stringify('development')
  },  
  API_SECRET_KEY: JSON.stringify('efb9erfdf6fd9vfd98vd8ssv'),
};

module.exports = {
  plugins: [  
      new webpack.DefinePlugin(GLOBALS)
  ],

 externals: {
    API_SECRET_KEY: 'API_SECRET_KEY'
   },
}

After that, API_SECRET_KEY became available in the browser. Until I registered it in externals - there was a situation similar to yours

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question