简体   繁体   English

Javascript:在 gulpfile.js 中获取 package.json 数据

[英]Javascript: get package.json data in gulpfile.js

Not a gulp-specific question per-se, but how would one get info from the package.json file within the gulpfile.js;本身不是 gulp 特定的问题,而是如何从 gulpfile.js 中的 package.json 文件中获取信息; For instance, I want to get the homepage or the name and use it in a task.例如,我想获取主页或名称并在任务中使用它。

This is not gulp specific.这不是特定于 gulp 的。

var p = require('./package.json')
p.homepage

UPDATE:更新:

Be aware that "require" will cache the read results - meaning you cannot require, write to the file, then require again and expect the results to be updated.请注意,“require”将缓存读取结果 - 这意味着您不能要求,写入文件,然后再次要求并期望结果被更新。

Don't use require('./package.json') for a watch process, as using require will resolve the module as the results of the first request.不要将require('./package.json')用于监视进程,因为使用require会将模块解析为第一个请求的结果。

So if you are editing your package.json those edits won't work unless you stop your watch process and restart it.因此,如果您正在编辑package.json除非您停止监视进程并重新启动它,否则这些编辑将不起作用。

For a gulp watch process it would be best to re-read the file and parse it each time that your task is executed, by using node's fs method对于gulp watch过程,最好在每次执行任务时重新读取文件并解析它,使用节点的fs方法

var fs = require('fs')
var json = JSON.parse(fs.readFileSync('./package.json'))

This is a good solution @Mangled Deutz.这是一个很好的解决方案@Mangled Deutz。 I myself first did that but it did not work (Back to that in a second), then I tried this solution:我自己首先这样做了,但它没有用(稍后再回到那个),然后我尝试了这个解决方案:

# Gulpfile.coffee
requireJSON = (file) ->
    fs = require "fs"
    JSON.parse fs.readFileSync file

Now you should see that this is a bit verbose (even though it worked).现在您应该看到这有点冗长(即使它有效)。 require('./package.json') is the best solution: require('./package.json')是最好的解决方案:

Tip提示

-remember to add './' in front of the file name. -记得在文件名前加上'./'。 I know its simple, but it is the difference between the require method working and not working.我知道它很简单,但它是 require 方法工作和不工作之间的区别。

If you are triggering gulp from NPM, like using " npm run build " or something如果你从 NPM 触发 gulp,比如使用“ npm run build ”或其他东西

(This only works for gulp run triggers by NPM) (这仅适用于 NPM 的 gulp 运行触发器)

process.env.npm_package_ Object process.env.npm_package_对象

this should be seprated by underscore for deeper objects.对于更深的对象,这应该用下划线分隔。

if you want to read some specific config in package.json like you want to read config object you have created in package.json如果您想读取 package.json 中的某些特定配置,就像您想读取您在 package.json 中创建的配置对象一样

scripts : {
   build: gulp 
},
config : {
   isClient: false.
}

then you can use然后你可以使用

process.env.npm_package_**config_isClient**

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

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