繁体   English   中英

如何向运行 javascript 文件的 package.json 文件添加自定义脚本?

[英]How do I add a custom script to my package.json file that runs a javascript file?

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

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

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

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

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

zsh: command not found: script1

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

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

如果您需要任何澄清,请告诉我。

自定义脚本

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

我创建了以下内容,它在我的系统上运行。 请试试这个:

包.json:

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

脚本1.js:

console.log('testing')

从命令行运行以下命令:

npm start

附加用例

我的 package.json 文件通常包含以下脚本,这使我能够查看我的文件以进行打字稿、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. 在 package.json 添加:

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

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

  4. 在终端中运行npm link

  5. 您现在可以从终端运行script1 ,它将运行node script1.js

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

让我们在脚本中说你想用一个命令运行 2 个命令:

"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

不客气😊😊

示例:

  "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": "node script1.js",
    "script2": "node script2.js"
}

命令

npm start
npm run script2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM