node.js 在 Vue.js 中使用环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50828904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:50:15  来源:igfitidea点击:

Using Environment Variables with Vue.js

node.jsvue.jsenvironment-variablesvue-clivue-cli-3

提问by Edgar Quintero

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 variables but this might be overkill for me. So I was wondering if there's something simple out of the box that works natively when working on a project already created with Vue CLI.

我一直在阅读官方文档,但找不到有关环境变量的任何内容。显然有一些社区项目支持环境变量,但这对我来说可能有点矫枉过正。所以我想知道在处理已经使用 Vue CLI 创建的项目时,是否有一些简单的开箱即用的东西可以在本地工作。

For example, I can see that if I do the following the right environment prints out meaning this is already setup?

例如,我可以看到,如果我执行以下操作,正确的环境会打印出来,这意味着这已经设置了吗?

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

I'm a kinda new to env variables and Node.

我对 env 变量和 Node.js 有点陌生。

FYI using Vue CLI version 3.0 beta.

仅供参考,使用 Vue CLI 3.0 测试版。

回答by RAH

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

如果您将 vue cli 与 Webpack 模板(默认配置)一起使用,您可以创建环境变量并将其添加到 .env 文件中。

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

这些变量将process.env.variableName在您的项目下自动访问。加载的变量也可用于所有 vue-cli-service 命令、插件和依赖项。

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

您有几个选项,这来自Environment Variables and Modes 文档

.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:

您的 .env 文件应如下所示:

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! :)

我的理解是,您需要做的就是创建 .env 文件并添加变量,然后您就可以开始了!:)

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

如以下评论所述:如果您使用的是 Vue cli 3,则只会加载以VUE_APP_开头的变量。

Don't forget to restart serveif it is currently running.

如果当前正在运行,请不要忘记重新启动服务

回答by Pedro Silva

If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

如果您使用的是 Vue cli 3,则只会加载以 VUE_APP_ 开头的变量。

In the root create a .env file with:

在根目录中创建一个 .env 文件:

VUE_APP_ENV_VARIABLE=value

And, if it's running, you need to restart serveso that the new env vars can be loaded.

而且,如果它正在运行,您需要重新启动服务,以便可以加载新的环境变量。

With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).

有了这个,您将能够在您的项目(.js 和 .vue 文件)中使用 process.env.VUE_APP_ENV_VARIABLE。

Update

更新

According to @ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.

根据@ali6p 的说法,使用 Vue Cli 3,不需要安装 dotenv 依赖项。

回答by ali6p

  1. Create two files in root folder (near by package.json) .envand .env.production
  2. Add variables to theese files with prefix VUE_APP_eg: VUE_APP_WHATEVERYOUWANT
  3. serveuses .envand builduses .env.production
  4. In your components (vue or js), use process.env.VUE_APP_WHATEVERYOUWANTto call value
  5. Don't forget to restart serveif it is currently running
  6. Clear browser cache
  1. 在根文件夹中创建两个文件(在 package.json 附近).env.env.production
  2. 将变量添加到这些带有前缀的文件中,VUE_APP_例如: VUE_APP_WHATEVERYOUWANT
  3. 服务用途.env建造用途.env.production
  4. 在您的组件(vue 或 js)中,使用process.env.VUE_APP_WHATEVERYOUWANT来调用 value
  5. 如果当前正在运行,请不要忘记重新启动服务
  6. 清除浏览器缓存

Be sure you are using vue-cli version 3 or above

确保您使用的是 vue-cli 版本 3 或更高版本

For more information: https://cli.vuejs.org/guide/mode-and-env.html

更多信息:https: //cli.vuejs.org/guide/mode-and-env.html

回答by benscabbia

In the root of your project create your environment files:

在项目的根目录中创建环境文件:

  • .env
  • .env.someEnvironment1
  • .env.SomeEnvironment2
  • .env
  • .env.someEnvironment1
  • .env.SomeEnvironment2

To then load those configs, you would specify the environment via modei.e.

然后加载这些配置,您将通过modeie指定环境

npm run serve --mode development //default mode
npm run serve --mode someEnvironment1

In your envfiles you simply declare the config as key-value pairs, but if you're using vue 3, you mustprefix with VUE_APP_:

在您的env文件中,您只需将配置声明为键值对,但如果您使用的是 vue 3,则必须添加前缀VUE_APP_

In your .env:

在您的.env 中

VUE_APP_TITLE=This will get overwritten if more specific available

.env.someEnvironment1:

.env.someEnvironment1:

VUE_APP_TITLE=My App (someEnvironment1)

You can then use this in any of your components via:

然后,您可以通过以下方式在任何组件中使用它:

myComponent.vue:

myComponent.vue:

<template>
  <div> 
    {{title}}
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  data() {
    return {
      title: process.env.VUE_APP_TITLE
    };
  }
};
</script>

Now if you ran the app without a modeit will show the 'This will get...' but if you specify a someEnvironment1as your modethen you will get the title from there.

现在,如果您在没有 a 的情况下运行该应用程序mode,它将显示“This will get...”,但如果您指定 asomeEnvironment1作为您的,mode那么您将从那里获得标题。

You can create configs that are 'hidden' from git by appending .localto your file: .env.someEnvironment1.local- very useful for when you have secrets.

您可以通过附加.local到您的文件来创建对 git “隐藏”的配置:.env.someEnvironment1.local- 当您有秘密时非常有用。

Read the docsfor more info.

阅读文档了解更多信息。

回答by Aaron McKeehan

A problem I was running into was that I was using the webpack-simple installfor 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.

遇到的一个问题是,我正在为 VueJS 使用 webpack-simple 安装,它似乎没有包含环境变量配置文件夹。所以我无法编辑 env.test、development 和 production.js 配置文件。创建它们也没有帮助。

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

其他答案对我来说不够详细,所以我只是“摆弄”了 webpack.config.js。以下工作得很好。

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

所以为了让环境变量工作,webpack.config.js 底部应该有以下内容:

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

基于上述,在生产中,您将能够获得 NODE_ENV 变量

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:

因此,在 Development 中,我现在可以访问这些环境变量:

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

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

这是整个 webpack.config.js 仅用于某些上下文:

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'"
      }
    })
  ]);

}

回答by drussell

This is how I edited my vue.config.js so that I could expose NODE_ENV to the frontend (I'm using Vue-CLI):

这就是我编辑 vue.config.js 的方式,以便我可以将 NODE_ENV 暴露给前端(我使用的是 Vue-CLI):

vue.config.js

vue.config.js

const webpack = require('webpack');

// options: https://github.com/vuejs/vue-cli/blob/dev/docs/config.md
module.exports = {
    // default baseUrl of '/' won't resolve properly when app js is being served from non-root location
    baseUrl: './',
    outputDir: 'dist',
    configureWebpack: {
        plugins: [
            new webpack.DefinePlugin({
                // allow access to process.env from within the vue app
                'process.env': {
                    NODE_ENV: JSON.stringify(process.env.NODE_ENV)
                }
            })
        ]
    }
};

回答by Matt Parkins

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):

除了前面的答案,如果您想访问 sass 中的 VUE_APP_* 环境变量(vue 组件的 sass 部分或 scss 文件),那么您可以将以下内容添加到 vue.config.js (如果您没有,您可能需要创建):

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.

字符串 sav 似乎被添加到处理之前的每个 sass 文件中,这对变量来说很好。您还可以在此阶段导入 mixin,使它们可用于每个 vue 组件的 sass 部分。

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

然后,您可以在 vue 文件的 sass 部分中使用这些变量:

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

or in a .scss file:

或在 .scss 文件中:

.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/

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

回答by jamesbellnet

For those using Vue CLI 3 and the webpack-simple install, Aaron's answerdid work for me however I wasn't keen on adding my environment variables to my webpack.config.jsas I wanted to commit it to GitHub. Instead I installed the dotenv-webpackplugin and this appears to load environment variables fine from a .envfile at the root of the project without the need to prepend VUE_APP_to the environment variables.

对于那些使用 Vue CLI 3 和 webpack-simple install 的人,Aaron 的回答对我有用,但是我并不热衷于将我的环境变量添加到我的,webpack.config.js因为我想将它提交到 GitHub。相反,我安装了dotenv-webpack插件,这似乎可以从.env项目根目录的文件中加载环境变量,而无需预先VUE_APP_添加环境变量。

回答by cagcak

In vue-cli version 3:

在 vue-cli 版本 3 中:

There are there options for .env files: Either you can use .envor:

.env 文件有一些选项:您可以使用.env或:

  • .env.test
  • .env.development
  • .env.production
  • .env.test
  • .env.development
  • .env.production

You can use custom .envvariables by using the prefix regex as /^/instead of /^VUE_APP_/in /node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

您可以.env通过使用前缀正则表达式 as/^/而不是/^VUE_APP_/in来使用自定义变量/node_modules/@vue/cli-service/lib/util/resolveClientEnv.js:prefixRE

This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .envfiles. Because everytime you npm install .., it will be overrided.

为了在测试、开发和.env文件生产等不同模式下开发开源应用程序,这当然是不推荐的。因为每次你npm install ..,它都会被覆盖。