Truca
Truca

Reputation: 195

Use version attribute of package.json in one of it's script

I need to use the version attribute of my package.json in one of it's scripts to put the version in the name of the JS bundle (i prefer to use the version as a unique identifier instead of a hash).

what i have:

"build-js": "browserify -t [ babelify --presets [ react es2015 ] ] js/components/App.js -o js/bundle.js"

what i need (i know it doesn't parse, but you get the idea):

"build-js": "browserify -t [ babelify --presets [ react es2015 ] ] js/components/App.js -o js/bundle."+this.version+".js"

Upvotes: 6

Views: 3199

Answers (2)

Churro
Churro

Reputation: 4366

When you run an npm script, npm will set all the package.json fields as environment variables that you can use:

https://docs.npmjs.com/cli/v9/using-npm/scripts#packagejson-vars

you can use the npm_package_version environment variable

Upvotes: 9

knownasilya
knownasilya

Reputation: 6143

You can do this with:

"build-js": "browserify -t [ babelify --presets [ react es2015 ] ] js/components/App.js -o js/bundle.$npm_package_version.js"

See this video for more details: https://egghead.io/lessons/tools-use-custom-config-settings-in-your-npm-scripts

P.S. It's worth not putting your bundle in the same directory as your source, usually it goes into dist/, e.g. dist/bundle.js. This way if you are publishing to npm you can ignore the unbuilt source directory. Or you can just remove the dist/ dir and rebuild, plus in the future you'll want other assets in dist as part of your build process.

Upvotes: 5

Related Questions