Using environment variables in npm scripts across platforms

折月煮酒 提交于 2019-12-06 18:39:15

问题


I am building a package.json and use "npm run" to run some scripts, to be exactly, https://docs.npmjs.com/misc/scripts.

My script would need to expand some environment variables and I want to make it cross platform compatible. For example, my script would say

"scripts": { "build": "md %npm_package_version%\helloworld" }

But it's currently running on Windows because the expansion of environment variables. Linux would use md $npm_package_version\helloworld.

Does npm comes with a mechanism to convert environment variables expansion so that it works across platforms?


回答1:


To make it cross-platform, use cross-var:

"scripts": {
  "build": "cross-var md %npm_package_version%\helloworld"
}



回答2:


npm doesn't appear to have a cross platform way to expand environment variables, but you do have node at your disposal, so I'd recommend implementing all your scripts as node scripts, then you can access process.env and cross-platform filesystem functions, like mkdirSync.

package.json

"scripts": {
  "build": "node utils/mdkir.js"
}

utils/mkdir.js

'use strict';

var fs = require('fs');

fs.mkdirSync(process.env.npm_package_version + '/helloworld');


来源:https://stackoverflow.com/questions/33331625/using-environment-variables-in-npm-scripts-across-platforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!