2016-03-28 94 views
19

我的package.json如下所示:如何在npm脚本中编写多行脚本?

{ 
    "name": "project", 
    "version": "1.0.0", 
    "description": "", 
    "main": "server.js", 
    "scripts": { 
    "lint": "./node_modules/eslint/bin/eslint.js --format \"./node_modules/eslint-friendly-formatter/index.js\" .", 
    "build:server": "./node_modules/babel-cli/bin/babel.js . -d dist/server --ignore node_modules,dist,client,public,webpack*" 
    } 
} 

正如你所看到的,lintbuild:server命令是很难读,我想打破他们多。

我已经尝试使用\,但它会抛出错误,如

npm ERR! Failed to parse json 
npm ERR! Unexpected token ' ' at 11:80 
npm ERR! :server": "./node_modules/babel-cli/bin/babel.js . -d dist/server \ 
npm ERR!                 ^

我怎样才能做到这一点?

只能编写另一个bash文件,如build.sh,并在npm脚本中使用它,如./build.sh server

回答

10

你不能这样做那。

以下代码是在read-json.js这是其中在run-script.js用于执行包node_modules/npm/node_modules/read-package-json$ npm run-script ~~$ npm run ~~这是它的别名。

function scriptpath (file, data, cb) { 
    if (!data.scripts) return cb(null, data) 
    var k = Object.keys(data.scripts) 
    k.forEach(scriptpath_, data.scripts) 
    cb(null, data) 
} 

function scriptpath_ (key) { 
    var s = this[key] 
    // This is never allowed, and only causes problems 
    if (typeof s !== 'string') return delete this[key] 

    var spre = /^(\.[\/\\])?node_modules[\/\\].bin[\\\/]/ 
    if (s.match(spre)) { 
    this[key] = this[key].replace(spre, '') 
    } 
} 

scriptpath_key就像是在你的代码"build:server"

this[key]就像代码中的"./node_modules/babel-cli/bin/babel.js . -d dist/server --ignore node_modules,dist,client,public,webpack*"一样。

所以,如果你写的这是不string型,换句话说,如果你不写在package.jsonstring文字的代码,它将除非你的包npm/read-package-json贡献是一个错误。

+0

好像代码可以支持一串字符串......我希望有一天有人会这样做。 –

39

您可以链接独立的任务:

这里有一个例子:

"scripts": { 
    "lint-jshint": "jshint --verbose --show-non-errors ./src/main/js", 
    "lint-eslint": "eslint ./src/main/js ./src/test/js", 
    "lint-csslint": "csslint ./src/main/js", 

    "lint": "npm run -s lint-jshint & npm run -s lint-eslint & npm run -s lint-csslint", 

    "pretest": "rimraf ./build/reports/tests && mkdirp ./build/reports/tests && npm run -s lint", 
    "test": "karma start ./src/test/resources/conf/karma.conf.js", 
    ... 

这里是一个不错的博客,我在那个时候使用: http://blog.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/