2016-03-28 65 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/