如何将自定义脚本添加到包中。Json文件,运行javascript文件?

我希望能够在将运行node script1.js的项目目录中执行命令script1

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

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

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

我的包裹。json文件,但当我尝试运行script1时,我得到以下输出:

zsh: command not found: script1

有人知道将上面提到的脚本添加到项目文件夹的必要步骤吗?

*注意:该命令不能添加到bash配置文件(不能是特定于机器的命令)

如果你需要澄清,请告诉我。

297463 次浏览

我已经创建了以下文件,它正在我的系统中工作。请试试这个:

package.json:

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

script1.js:

console.log('testing')

在命令行中运行以下命令:

npm start

附加用例

我的包。Json文件通常有以下脚本,这使我能够观察我的文件的typescript, sass编译和运行服务器以及。

 "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. < p >在包中。json添加:

    "bin":{
    "script1": "bin/script1.js"
    }
    
  2. Create a bin folder in the project directory and add file runScript1.js with the code:

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

  4. Run npm link in terminal

  5. From terminal you can now run script1 which will run node script1.js

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

自定义脚本

npm run-script <custom_script_name>

npm run <custom_script_name>

在你的例子中,你想要运行npm run-script script1npm run script1

看到https://docs.npmjs.com/cli/run-script

生命周期脚本

Node还允许你为某些生命周期事件运行自定义脚本,比如在npm install运行之后。这些可以在在这里中找到。

例如:

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

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

例子:

  "scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"build_c": "ng build --prod && del \"../../server/front-end/*.*\" /s /q & xcopy /s dist \"../../server/front-end\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},

正如你所看到的,“build_c”脚本正在构建angular应用程序,然后从一个目录中删除所有旧文件,最后复制结果构建文件。

假设在脚本中,你想用一个命令运行两个命令:

"scripts":{
"start":"any command",
"singleCommandToRunTwoCommand":"some command here && npm start"
}

现在转到你的终端并运行npm run singleCommandToRunTwoCommand

假设我的“package.json”中有这一行脚本;

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"export_advertisements": "node export.js advertisements",
"export_homedata": "node export.js homedata",
"export_customdata": "node export.js customdata",
"export_rooms": "node export.js rooms"
},

现在要运行脚本“export_advertisements&;”,我将简单地转到终端并输入

npm run export_advertisements