如何将自定义脚本添加到运行JavaScript文件的package.json文件中?

我希望能够在将运行node script1.js的项目目录中执行命令script1script1.js是同一个目录中的文件。 该命令需要特定于项目目录,这意味着如果我发送其他人项目文件夹,他们将能够运行相同的命令。

到目前为止,我已经尝试添加:

 "scripts": { "script1": "node script1.js" } 

到我的package.json文件,但是当我尝试运行script1我得到以下输出:

 zsh: command not found: script1 

有没有人知道将上述脚本添加到项目文件夹所需的步骤?

*注意:该命令不能添加到bashconfiguration文件(不能是一个特定于计算机的命令)

请让我知道,如果你需要任何澄清。

自定义脚本

npm run-script <custom_script_name>

要么

npm run <custom_script_name>

在你的例子中,你会想运行npm run-script script1或者npm run script1

请参阅https://docs.npmjs.com/cli/run-script

生命周期脚本

Node还允许您为特定的生命周期事件运行自定义脚本,就像npm install之后一样。 这些可以在这里find。

例如:

 "scripts": { "postinstall": "electron-rebuild", }, 

这将在npm install命令之后运行electron-rebuild

我已经创build了下面的,并在我的系统上工作。 请试试这个

的package.json:

 { "name": "test app", "version": "1.0.0", "scripts": { "start": "node script1.js" } } 

script1.js:

 console.log('testing') 

从命令行运行以下命令

npm开始

额外的用例我的package.json文件通常具有以下脚本。 这使我可以观看我的文件打字稿,杂志和运行服务器。

  "scripts": { "start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ", "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "typings": "typings", "postinstall": "typings install" } 

步骤如下:

  1. 在package.json中添加:

     "bin":{ "script1": "bin/script1.js" } 
  2. 在项目目录中创build一个bin文件夹,并用代码添加文件runScript1.js

     #! /usr/bin/env node var shell = require("shelljs"); shell.exec("node step1script.js"); 
  3. 在terminal中运行npm install shelljs

  4. 在terminal中运行npm link

  5. 现在可以从terminal运行script1 ,它将运行node script1.js

参考: http : //blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm