Using Environment Variables with Vue.js

后端 未结 9 1332
礼貌的吻别
礼貌的吻别 2020-11-29 18:22

I\'ve been reading the official docs and I\'m unable to find anything on environment variables. Apparently there are some community projects that support environment variabl

相关标签:
9条回答
  • 2020-11-29 18:49

    In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):

    let sav = "";
    for (let e in process.env) {
        if (/VUE_APP_/i.test(e)) {
            sav += `$${e}: "${process.env[e]}";`;
        }
    }
    
    module.exports = {
        css: {
            loaderOptions: {
                sass: {
                    data: sav,
                },
            },
        },
    }
    

    The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.

    You can then use these variables in your sass section of a vue file:

    <style lang="scss">
    .MyDiv {
        margin: 1em 0 0 0;
        background-image: url($VUE_APP_CDN+"/MyImg.png");
    }
    </style>
    

    or in a .scss file:

    .MyDiv {
        margin: 1em 0 0 0;
        background-image: url($VUE_APP_CDN+"/MyImg.png");
    }
    

    from https://www.matt-helps.com/post/expose-env-variables-vue-cli-sass/

    0 讨论(0)
  • 2020-11-29 18:50

    A problem I was running into was that I was using the webpack-simple install for VueJS which didn't seem to include an Environment variable config folder. So I wasn't able to edit the env.test,development, and production.js config files. Creating them didn't help either.

    Other answers weren't detailed enough for me, so I just "fiddled" with webpack.config.js. And the following worked just fine.

    So to get Environment Variables to work, the webpack.config.js should have the following at the bottom:

    if (process.env.NODE_ENV === 'production') {
      module.exports.devtool = '#source-map'
      // http://vue-loader.vuejs.org/en/workflow/production.html
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"production"'
          }
        }),
        new webpack.optimize.UglifyJsPlugin({
          sourceMap: true,
          compress: {
            warnings: false
          }
        }),
        new webpack.LoaderOptionsPlugin({
          minimize: true
        })
      ])
    }
    

    Based on the above, in production, you would be able to get the NODE_ENV variable

    mounted() {
      console.log(process.env.NODE_ENV)
    }
    

    Now there may be better ways to do this, but if you want to use Environment Variables in Development you would do something like the following:

    if (process.env.NODE_ENV === 'development') {
    
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"development"'
          }
        })
      ]);
    
    } 
    

    Now if you want to add other variables with would be as simple as:

    if (process.env.NODE_ENV === 'development') {
    
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"development"',
            ENDPOINT: '"http://localhost:3000"',
            FOO: "'BAR'"
          }
        })
      ]);
    }
    

    I should also note that you seem to need the "''" double quotes for some reason.

    So, in Development, I can now access these Environment Variables:

    mounted() {
      console.log(process.env.ENDPOINT)
      console.log(process.env.FOO)
    }
    

    Here is the whole webpack.config.js just for some context:

    var path = require('path')
    var webpack = require('webpack')
    
    module.exports = {
      entry: './src/main.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'build.js'
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'vue-style-loader',
              'css-loader'
            ],
          },      {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
              loaders: {
              }
              // other vue-loader options go here
            }
          },
          {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
          },
          {
            test: /\.(png|jpg|gif|svg)$/,
            loader: 'file-loader',
            options: {
              name: '[name].[ext]?[hash]'
            }
          }
        ]
      },
      resolve: {
        alias: {
          'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
      },
      devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true
      },
      performance: {
        hints: false
      },
      devtool: '#eval-source-map'
    }
    
    if (process.env.NODE_ENV === 'production') {
      module.exports.devtool = '#source-map'
      // http://vue-loader.vuejs.org/en/workflow/production.html
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"production"'
          }
        }),
        new webpack.optimize.UglifyJsPlugin({
          sourceMap: true,
          compress: {
            warnings: false
          }
        }),
        new webpack.LoaderOptionsPlugin({
          minimize: true
        })
      ])
    }
    
    if (process.env.NODE_ENV === 'development') {
    
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"development"',
            ENDPOINT: '"http://localhost:3000"',
            FOO: "'BAR'"
          }
        })
      ]);
    
    }
    
    0 讨论(0)
  • 2020-11-29 18:51

    If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.

    The variables will automatically be accessible under process.env.variableName in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.

    You have a few options, this is from the Environment Variables and Modes documentation:

    .env                # loaded in all cases
    .env.local          # loaded in all cases, ignored by git
    .env.[mode]         # only loaded in specified mode
    .env.[mode].local   # only loaded in specified mode, ignored by git
    

    Your .env file should look like this:

    VUE_APP_MY_ENV_VARIABLE=value
    VUE_APP_ANOTHER_VARIABLE=value
    

    It is my understanding that all you need to do is create the .env file and add your variables then you're ready to go! :)

    As noted in comment below: If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

    Don't forget to restart serve if it is currently running.

    0 讨论(0)
提交回复
热议问题