简体   繁体   English

在Windows上的package.json中外部定位的'npm run'脚本?

[英]Externally-located 'npm run' scripts in package.json on Windows?

As we know, you can run arbitrary commands using npm run by adding a scripts hash to your package.json : 我们知道,您可以通过向package.json添加scripts哈希来使用npm run运行任意命令:

"scripts": {
    "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js"
}

Which would then be run with npm run build-js . 然后使用npm run build-js

You can also move these commands out into separate scripts, such as bash scripts, as such: 您还可以将这些命令移到单独的脚本中,例如bash脚本,如下所示:

"scripts": {
    "build-js": "bin/build.sh"
}

This obviously doesn't natively work on Windows, due to Windows not being capable of running bash scripts. 由于Windows无法运行bash脚本,因此显然本身不能在Windows上运行。 You can install bash ports and such, but I'd love to be able to use some sort of native Windows construct for doing the same thing. 您可以安装bash端口等,但我希望能够使用某种本机Windows构造来执行相同的操作。

I've tried some other approaches, including using child_process.exec to run arbitrary commands from within a standard node script file: 我尝试过其他一些方法,包括使用child_process.exec从标准节点脚本文件中运行任意命令:

"scripts": {
    "build-js": "node bin/build.js"
}

But I've noticed child_process chokes on relatively large/intensive operations, making it implausible to use. 但我注意到相对较大/密集型操作的child_process扼流圈,使得使用起来难以置信。

Is there a Windows-specific (or even better, cross-platform) way to move these package.json npm run scripts out into separate files? 是否有特定于Windows(甚至更好,跨平台)的方式将这些package.json npm run脚本移动到单独的文件中? Preferably one that doesn't require bash? 最好是不需要bash的?

From a helpful article on using NPM as a build tool, why not simply use a JavaScript file? 一篇关于使用NPM作为构建工具的有用文章 ,为什么不简单地使用JavaScript文件呢?

Here's the example given in the article (slightly modified for clarity): 以下是文章中给出的示例(为清晰起见略作修改):

// scripts/favicon.js

var favicons = require('favicons');  
var path = require('path');  

favicons({  
  source: path.resolve('../assets/images/logo.png'),
  dest: path.resolve('../dist/'),
});


// package.json

"scripts": {
  "build-favicon": "node scripts/favicon.js",
},
"devDependencies": {
  "favicons": "latest",
}

Which would be run in the terminal with the command npm run build-favicon 使用命令npm run build-favicon在终端中npm run build-favicon

Using node to run a JS file is an option, but if you need to run system commands on both Windows and *NIX, that would make the script messy. 使用节点运行JS文件是一个选项,但是如果你需要在Windows和* NIX上运行系统命令,那将使脚本变得混乱。 For cross-platform scripts, try out the shelljs package. 对于跨平台脚本,请尝试使用shelljs包。

Using the make command is also a nice option. 使用make命令也是一个不错的选择。

Makefile Makefile文件

build-js:
    browserify browser/main.js | uglifyjs -mc > static/bundle.js

package.json 的package.json

"scripts": {
    "build-js": "make build-js",
}

You can find more about make here . 你可以在这里找到更多关于make 信息

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

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