簡體   English   中英

如何在 npm 腳本中編寫多行腳本?

[英]How can I write multiline scripts in npm scripts?

我的 package.json 如下所示:

{
  "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!                                                                   ^

我該怎么做?

只是為了編寫另一個像build.sh這樣的 bash 文件並在像./build.sh server這樣的 npm 腳本中使用它?

您可以鏈接獨立的任務。

下面是一個例子:

"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",
    ...

這是我當時使用的一個不錯的博客: https : //www.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/

你不能那樣做。

以下代碼位於node_modules/npm/node_modules/read-package-json包中的read-json.js ,該包在run-script.js用於執行$ 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 text ,除非你對包npm/read-package-json做出貢獻,否則它將是一個錯誤。

另一種常見的替代方法是編寫一個引用本地 bash 腳本的npm命令(在那里你有更多的能力做你想做的事)。

# package.json
{
  "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": "./build-server.sh"
  }
}
# build-server.sh
#!/bin/bash

./node_modules/babel-cli/bin/babel.js . \
  -d dist/server \
  --ignore \
    node_modules,\
    dist,\
    client,\
    public,\
    webpack*

注意:確保您授予自己運行該文件的權限; 否則你會遇到權限問題

sudo chmod 755 'build-server.sh'

請參閱: 在 mac 提示“權限被拒絕”上運行腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM