[removed] get package.json data in gulpfile.js

前端 未结 4 1224
时光说笑
时光说笑 2020-12-07 19:44

Not a gulp-specific question per-se, but how would one get info from the package.json file within the gulpfile.js; For instance, I want to get the homepage or the name and u

相关标签:
4条回答
  • 2020-12-07 20:08

    Don't use require('./package.json') for a watch process, as using require will resolve the module as the results of the first request.

    So if you are editing your package.json those edits won't work unless you stop your watch process and restart it.

    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

    var fs = require('fs')
    var json = JSON.parse(fs.readFileSync('./package.json'))
    
    0 讨论(0)
  • 2020-12-07 20:08

    If you are triggering gulp from NPM, like using "npm run build" or something

    (This only works for gulp run triggers by NPM)

    process.env.npm_package_Object

    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

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

    then you can use

    process.env.npm_package_**config_isClient**
    
    0 讨论(0)
  • 2020-12-07 20:26

    This is not gulp specific.

    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.

    0 讨论(0)
  • 2020-12-07 20:30

    This is a good solution @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:

    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.

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