简体   繁体   English

Vue cli 3 显示 package.json 中的信息

[英]Vue cli 3 display info from the package.json

In a vue cli 3 project I want to display a version number in the webpage.在 vue cli 3 项目中,我想在网页中显示版本号。 The version number lies in the package.json file.版本号位于package.json文件中。

The only reference to this that I found is this link in the vue forum .我找到的对此的唯一参考是 vue 论坛中的这个链接

However, I can't get the proposed solution to work.但是,我无法使建议的解决方案起作用。

Things I tried我尝试过的事情

  1. Use webpack.definePlugin as in the linked resource:在链接的资源中使用webpack.definePlugin

vue.config.js

const webpack = require('webpack');

module.exports = {
  lintOnSave: true,

  configureWebpack: config => {
    return {
      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            VERSION: require('./package.json').version,
          }
        })
      ]
    }
  },
}

Then in main.ts I read process.env , but it does not contain VERSION (I tried several variants to this, like generating a PACKAGE_JSON field like in the linked page, and generating plain values like 'foo' instead of reading from package-json ).然后在main.ts我读process.env ,但它不包含版本(我试过几个变种于此,就像在链接页面生成PACKAGE_JSON场等,生成普通值像“富”,而不是从阅读package-json )。 It never worked, it is like the code is being ignored.它从未奏效,就像代码被忽略了一样。 I guess the process.env is being redefined later by vue webpack stuff.我想process.env稍后会被 vue webpack 的东西重新定义。

The process log in main.ts contains, however, all the stuff that process usually contains in a vue-cli project, like the mode and the VUE_APP variables defined in .env files.然而, main.ts中的process日志包含process通常包含在 vue-cli 项目中的所有内容,例如模式和.env文件中定义的 VUE_APP 变量。

  1. Try to write to process right on the configure webpack function,尝试在配置 webpack 功能上写入process

like:喜欢:

 configureWebpack: config => {
   process.VERSION = require('./package.json').version
 },

(to be honest I did not have much hope with this, but had to try). (说实话,我对此没有太大希望,但不得不尝试)。

  1. Tried the other solution proposed in the linked page,尝试了链接页面中提出的其他解决方案,

like:喜欢:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.plugin('define').tap( ([options = {}]) => {
      return [{
        ...options, // these are the env variables from your .env file, if any arr defined
        VERSION: JSON.stringify(require('./package.json').version)
      }]
    })
  }
} 

But this fail silently too.但这也无声无息地失败了。

  1. Use the config.plugin('define') syntax suggested by @Oluwafemi,使用@Oluwafemi 建议的config.plugin('define')语法,

like:喜欢:

chainWebpack: (config) => {
  return config.plugin('define').tap(
    args => merge(args, [VERSION])
  )
},

Where VERSION is a local variable defined as:其中VERSION是一个局部变量,定义为:

const pkgVersion = require('./package.json').version;

const VERSION = {
  'process.env': {
    VUE_APP_VERSION: JSON.stringify(pkgVersion)
  }
}

But this is not working either.但这也行不通。


I am re-starting the whole project everytime, so that's not the reason why the process stuff does not show up.我每次都重新启动整个项目,所以这不是流程内容不显示的原因。

My vue-cli version is 3.0.1 .我的 vue-cli 版本是 3.0.1

I am adding my 2 cents, as I found a shorter way and apparently the right way ( https://docs.npmjs.com/misc/scripts#packagejson-vars )我加了 2 美分,因为我找到了一种更短的方法,而且显然是正确的方法( https://docs.npmjs.com/misc/scripts#packagejson-vars

Add this in your vue.config.file before the export, not inside:在导出之前将其添加到 vue.config.file 中,而不是在里面:

process.env.VUE_APP_VERSION = process.env.npm_package_version

And voilà!瞧!

You can then use it from a component with process.env.VUE_APP_VERSION然后您可以从带有process.env.VUE_APP_VERSION的组件中使用它

TLDR TLDR

The following snippet in the vue.config.js file will do the trick, and will allow you to access the version of your app as APPLICATION_VERSION : vue.config.js文件中的以下代码段将vue.config.js ,并允许您以APPLICATION_VERSION访问应用程序的版本:

module.exports = {
  configureWebpack: config => {
    return {
      plugins: [
        new webpack.DefinePlugin({
          'APPLICATION_VERSION': JSON.stringify(require('./package.json').version),
        })
      ]
    }
  },
}

TIP:提示:

Don't even try to add some key to process.env via webpack.definePlugin : it won't work as you probably expect.甚至不要尝试通过webpack.definePluginprocess.env添加一些键:它不会像您期望的那样工作。

Why my previous efforts did not work为什么我之前的努力没有奏效

At the end, I solved the issue via webpack.DefinePlugin .最后,我通过webpack.DefinePlugin解决了这个问题。 The main issue I had is that the original solution I found was using definePlugin to write to a process.env.PACKAGE_JSON variable.我遇到的主要问题是我发现的原始解决方案是使用definePlugin写入process.env.PACKAGE_JSON变量。

This suggests that definePlugin somehow allows to add variables to process or process.env , which is not the case.这表明definePlugin以某种方式允许向processprocess.env添加变量,但事实并非如此。 Whenever I did log process.env in the console, I didn't find the variables I was trying to push into process.env : so I though the definePlugin tech was not working.每当我在控制台中记录process.env时,我都没有找到我试图推入process.env的变量:所以我认为definePlugin技术不起作用。

Actually, what webpack.definePlugin does is to check for strings at compile time and change them to its value right on your code.实际上, webpack.definePlugin所做的就是在编译时检查字符串并将它们更改为代码中的正确值。 So, if you define an ACME_VERSION variable via:因此,如果您通过以下方式定义ACME_VERSION变量:

module.exports = {
  lintOnSave: true,

  configureWebpack: config => {
    return {
      plugins: [
        new webpack.DefinePlugin({
          'ACME_VERSION': 111,
        })
      ]
    }
  },
}

and then, in main.js you print console.log(ACME_VERSION) , you will get 111 properly logged .然后,在main.js您打印console.log(ACME_VERSION) ,您将获得111正确记录

Now, however, this is just a string change at compile time.然而,现在这只是编译时的字符串更改。 If instead of ACME_VERSION you try to define process.env.VUE_APP_ACME_VERSION ...如果您尝试定义process.env.VUE_APP_ACME_VERSION而不是ACME_VERSION ...

when you log process.env the VUE_APP_ACME_VERSION key won't show up in the object.当您记录process.envVUE_APP_ACME_VERSION键不会显示在对象中。 However , a raw console.log('process.env.VUE_APP_ACME_VERSION') will yield 111 as expected.但是,原始console.log('process.env.VUE_APP_ACME_VERSION')将按预期产生111

So, basically, original link and the proposed solutions were correct to some degree.因此,基本上,原始链接和建议的解决方案在某种程度上是正确的。 However, nothing was really being added to the process object.但是,并没有真正向process对象添加任何内容。 I was logging proccess.env during my initial tries, so I didn't see anything working.我在最初的尝试中记录了proccess.env ,所以我没有看到任何工作。

Now, however, since the process object is not being modified, I strongly suggest anyone trying to load variables to their vue app at compile time not to use it.然而,现在由于process对象没有被修改,我强烈建议任何试图在编译时将变量加载到他们的 vue 应用程序的人不要使用它。 Is misleading at best.充其量是误导。

When building the Vue app, environment variables that don't begin with the VUE_APP_ prefix are filtered out .构建 Vue 应用程序时, 过滤掉不以VUE_APP_前缀开头的环境变量 NODE_ENV and BASE_URL environment variables are the exception. NODE_ENVBASE_URL环境变量是例外。

The above information applies when the environment variables are set prior to building the Vue app and not in this situation.上述信息适用于在构建 Vue 应用程序之前设置环境变量而不是这种情况。

In a situation where environment variables are set during the build, it's important to look at what Vue CLI is doing.在构建期间设置环境变量的情况下,查看Vue CLI正在做什么很重要。

The Vue CLI uses webpack.DefinePlugin to set environment variables using the object returned from the call to resolveClientEnv . Vue CLI 使用webpack.DefinePlugin使用调用resolveClientEnv返回的对象设置环境变量。

resolveClientEnv returns resolveClientEnv返回

{
   'process.env': {}
}

This means when configuring your environment variables at build time, you need to come upon a way to merge with the existing one.这意味着在构建时配置环境变量时,您需要想办法与现有变量合并。 You need to perform a deep merge of both arrays, so that value for process.env key is an object containing keys from the resolved client environment and your keys.您需要对两个数组执行深度合并,以便process.env键的值是一个包含来自已解析客户端环境的键和您的键的对象。

chainWebpack key in the default export for vue.config.js is just about one of the ways to get this done. chainWebpack在默认出口重点vue.config.js正要来完成这件事的方式之一。

The arguments passed to initialize the DefinePlugin can be merged with new environment variables that you like to configure using the underlying webpack-chain API.用于初始化DefinePlugin的参数可以与您喜欢使用底层webpack-chain API 配置的新环境变量合并。 Here is an example:下面是一个例子:

// vue.config.js

const merge = require('deepmerge');
const pkgVersion = require('./package.json').version;

const VERSION = {
   'process.env': {
     VERSION: JSON.stringify(pkgVersion)
   }
}

module.exports = {
  chainWebpack: config => 
    config
      .plugin('define')
      .tap(
          args => merge(args, [VERSION])
      )
}

Your initial attempt was fine, you were just missing the JSON.stringify part:你最初的尝试很好,你只是错过了JSON.stringify部分:

const webpack = require('webpack');

module.exports = {    
  configureWebpack: config => {
    return {
      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            VERSION: JSON.stringify(require('./package.json').version),
          }
        })
      ]
    }
  },
}

Edit: although the webpack docs recommend the 'process.env.VERSION' way (yellow panel):编辑:虽然webpack 文档推荐'process.env.VERSION'方式(黄色面板):

new webpack.DefinePlugin({
  'process.env.VERSION': JSON.stringify(require('./package.json').version),
}),

You can simply import your package.json file and use its variables.您可以简单地导入 package.json 文件并使用其变量。

import { version } from "../../package.json";

console.log(version)

If you are using Webpack, you can inject the variable in the following way:如果您使用的是 Webpack,则可以通过以下方式注入变量:

// webpack.config.js
  plugins: [
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(require("package.json").version)
    })
  ]

// any-module.js
console.log("Version: " + VERSION);

https://github.com/webpack/webpack/issues/237 https://github.com/webpack/webpack/issues/237

Official solutions tend to be more reliable Modes and Environment Variables |官方解决方案往往更可靠Modes and Environment Variables | Vue CLI 命令行界面

TIP提示

You can have computed env vars in your vue.config.js file.您可以在 vue.config.js 文件中计算环境变量。 They still need to be prefixed with VUE_APP_.它们仍然需要以 VUE_APP_ 为前缀。 This is useful for version info这对版本信息很有用

process.env.VUE_APP_VERSION = require('./package.json').version

module.exports = {
  // config
}

I attempted the accepted answer, and had errors.我尝试了接受的答案,但有错误。 However, in the vue docs, I was able to find an answer similar (but not quite) that of @antoni 's answer.但是,在 vue 文档中,我能够找到与@antoni的答案相似(但不完全相同)的答案。

In short, just have the following in vue.config.js :简而言之,只需在vue.config.js包含以下vue.config.js

process.env.VUE_APP_VERSION = require('./package.json').version

module.exports = {
  // config
}

Docs 2020-10-27 : 文件 2020-10-27

You can access env variables in your application code:您可以在应用程序代码中访问 env 变量:

process.env.VUE_APP_NOT_SECRET_CODE = require('./package.json').version

During build, process.env.VUE_APP_NOT_SECRET_CODE will be replaced by the corresponding value.在构建process.env.VUE_APP_NOT_SECRET_CODEprocess.env.VUE_APP_NOT_SECRET_CODE将被相应的值替换。 In the case of VUE_APP_NOT_SECRET_CODE=some_value , it will be replaced by "some_value" .VUE_APP_NOT_SECRET_CODE=some_value的情况下,它将被替换为"some_value"

In addition to VUE_APP_* variables, there are also two special variables that will always be available in your app code:除了VUE_APP_*变量之外,还有两个特殊变量在您的应用程序代码中始终可用:

  • NODE_ENV - this will be one of "development", "production" or "test" depending on the mode the app is running in. NODE_ENV - 这将是“开发”、“生产”或“测试”之一,具体取决于应用程序运行的模式。

  • BASE_URL - this corresponds to the publicPath option in vue.config.js and is the base path your app is deployed at. BASE_URL - 这对应于 vue.config.js 中的 publicPath 选项,并且是您的应用程序部署的基本路径。

The answer for this on the official VueJS forum is like so:官方 VueJS 论坛上的答案是这样的:

chainWebpack: config => {
  config
    .plugin('define')
      .tap(args => {
        let v = JSON.stringify(require('./package.json').version)
        args[0]['process.env']['VERSION'] = v
        return args
      })
}

Description描述

Add this line to your vue.config.js file将此行添加到您的vue.config.js文件中

module.exports = {
    ...
    chainWebpack: config => {
        config
            .plugin('define')
            .tap(args => {
                let v = JSON.stringify(require('./package.json').version)
                args[0]['process.env']['VERSION'] = v
                return args
            })
    }
};

Then you can use this in your vue files like so:然后你可以在你的 vue 文件中使用它,如下所示:

version: function () {
            return process.env.VERSION
        }

A one liner alternative:单班轮替代方案:

//script tag
let packageJsonInfo = require("../../package.json");

//Then you can for example, get the version no
packageJsonInfo.version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM