使用 package.json 全局和本地安装依赖项

发布于 2024-11-16 22:58:03 字数 373 浏览 0 评论 0原文

使用 npm,我们可以使用 -g 选项全局安装模块。我们如何在 package.json 文件中做到这一点?

假设,这些是我在 package.json 文件中的依赖项

"dependencies": {
    "mongoose": "1.4.0",
    "node.io" : "0.3.3",
    "jquery"  : "1.5.1",
    "jsdom"   : "0.2.0",
    "cron"    : "0.1.2"
  }

,当我运行 npm install 时,我只想全局安装 node.io ,其余的应该在本地安装。有这个选择吗?

Using npm we can install the modules globally using -g option. How can we do this in the package.json file?

Suppose, these are my dependencies in package.json file

"dependencies": {
    "mongoose": "1.4.0",
    "node.io" : "0.3.3",
    "jquery"  : "1.5.1",
    "jsdom"   : "0.2.0",
    "cron"    : "0.1.2"
  }

When i run npm install, I want only node.io to be installed globally, the rest others should be installed locally. Is there an option for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

长梦不多时 2024-11-23 22:58:03

新注意:您可能不想或不需要这样做。您可能想要做的只是将构建/测试等的这些类型的命令依赖项放在 package.json 的 devDependencies 部分中。 每当您在 package.json 中使用 scripts 中的内容时,您的 devDependency 命令(在 n​​ode_modules/.bin 中)的行为就好像它们在您的路径中一样。

例如:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

然后在 package.json 中。 json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

然后在命令提示符下,您可以运行:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

New NEW 注意:现在我们已经有了 npx,它允许您运行 devDependency 命令,而无需添加它们给你的scripts 部分(如果需要)。
例如:

npx webpack

但是如果你真的想要全局安装,你可以在 package.json 的脚本部分添加预安装:

"scripts": {
  "preinstall": "npm i -g themodule"
}

所以实际上我的 npm install 再次执行 npm install ...这很奇怪,但似乎有效。

注意:如果您使用最常见的 npm 设置(其中全局 Node 包安装所需的 sudo),则可能会遇到问题。一种选择是更改您的 npm 配置,这样就没有必要了:

npm config set prefix ~/npm,通过附加 < 将 $HOME/npm/bin 添加到 $PATH code> 将 PATH=$HOME/npm/bin:$PATH 导出到您的 ~/.bashrc

另一个可能更好的选择是仅使用 nvm 来管理 Node,这样您就不会遇到这个问题。

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

For example:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

New NEW Note: For awhile now we have had npx, which allows you to run the devDependencies commands without needing to add them to your scripts section (if you want).
For example:

npx webpack

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

So actually my npm install executes npm install again ... Which is weird but seems to work.

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.

Another, probably better option is to just use nvm to manage Node and you won't have that problem.

绾颜 2024-11-23 22:58:03

由于下面描述的缺点,我建议遵循已接受的答案:

使用npm install --save-dev [package_name]然后执行脚本:

$ npm run lint
$ npm 运行构建
$ npm 测试

我原来的但不推荐的答案如下。


您可以将包添加到您的 devDependency (--save-dev),然后从项目内的任何位置运行二进制文件,而不是使用全局安装:

"$(npm bin)/<executable_name>" <arguments>...

在您的情况下:

"$(npm bin)"/node.io --help

这位工程师提供了npm-exec 别名作为快捷方式。 该工程师使用名为 env.sh 的 shell 脚本。但我更喜欢直接使用 $(npm bin) ,以避免任何额外的文件或设置。

尽管它使每个调用变得更大一些,但它应该正常工作,防止:

  • 与全局包 (@nalply) 的潜在依赖冲突、
  • 需要 sudo
  • 需要设置一个 npm 前缀(尽管我还是建议使用一个)

缺点:

  • $(npm bin) 在 Windows 上不起作用。
  • 开发树中更深层次的工具不会出现在 npm bin 文件夹中。 (安装 npm-runnpm-which 来找到它们。)

似乎更好的解决方案是将常见任务(例如构建和缩小)放在<一href="https://github.com/npm/npm/issues/3738#issuecomment-22505089" rel="nofollow noreferrer">package.json 的“脚本”部分 ,正如 Jason 上面所演示的那样。

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

我偏爱纯白色 2024-11-23 22:58:03

这有点旧,但我遇到了要求,所以这是我想出的解决方案。

问题

我们的开发团队维护着许多 .NET Web 应用程序产品,我们正在迁移到 AngularJS/Bootstrap。 VS2010 不太适合自定义构建流程,而我的开发人员通常会开发我们产品的多个版本。我们的 VCS 是 Subversion(我知道,我知道。我正在尝试迁移到 Git,但我讨厌的营销人员要求很高),单个 VS 解决方案将包含多个单独的项目。我需要我的员工有一个通用的方法来初始化他们的开发环境,而不必在同一台机器上多次安装相同的 Node 包(gulp、bower 等)。

TL;DR:

  1. 需要“npm install”来安装全局 Node/Bower 开发环境以及 .NET 产品所需的所有本地包。

  2. 仅当尚未安装全局包时才应安装。

  3. 必须自动创建全局包的本地链接。

解决方案

我们已经拥有一个由所有开发人员和所有产品共享的通用开发框架,因此我创建了一个 NodeJS 脚本来在需要时安装全局包并创建本地链接。该脚本位于相对于产品基础文件夹的“....\SharedFiles”中:

/*******************************************************************************
* $Id: npm-setup.js 12785 2016-01-29 16:34:49Z sthames $
* ==============================================================================
* Parameters: 'links' - Create links in local environment, optional.
* 
* <p>NodeJS script to install common development environment packages in global
* environment. <c>packages</c> object contains list of packages to install.</p>
* 
* <p>Including 'links' creates links in local environment to global packages.</p>
* 
* <p><b>npm ls -g --json</b> command is run to provide the current list of 
* global packages for comparison to required packages. Packages are installed 
* only if not installed. If the package is installed but is not the required 
* package version, the existing package is removed and the required package is 
* installed.</p>.
*
* <p>When provided as a "preinstall" script in a "package.json" file, the "npm
* install" command calls this to verify global dependencies are installed.</p>
*******************************************************************************/
var exec = require('child_process').exec;
var fs   = require('fs');
var path = require('path');

/*---------------------------------------------------------------*/
/* List of packages to install and 'from' value to pass to 'npm  */
/* install'. Value must match the 'from' field in 'npm ls -json' */
/* so this script will recognize a package is already installed. */
/*---------------------------------------------------------------*/
var packages = 
  {
  "bower"                      :                      "[email protected]", 
  "event-stream"               :               "[email protected]",
  "gulp"                       :                       "[email protected]",
  "gulp-angular-templatecache" : "[email protected]",
  "gulp-clean"                 :                 "[email protected]", 
  "gulp-concat"                :                "[email protected]",
  "gulp-debug"                 :                 "[email protected]",
  "gulp-filter"                :                "[email protected]",
  "gulp-grep-contents"         :         "[email protected]",
  "gulp-if"                    :                    "[email protected]", 
  "gulp-inject"                :                "[email protected]", 
  "gulp-minify-css"            :            "[email protected]",
  "gulp-minify-html"           :           "[email protected]",
  "gulp-minify-inline"         :         "[email protected]",
  "gulp-ng-annotate"           :           "[email protected]",
  "gulp-processhtml"           :           "[email protected]",
  "gulp-rev"                   :                   "[email protected]",
  "gulp-rev-replace"           :           "[email protected]",
  "gulp-uglify"                :                "[email protected]",
  "gulp-useref"                :                "[email protected]",
  "gulp-util"                  :                  "[email protected]",
  "lazypipe"                   :                   "[email protected]",
  "q"                          :                          "[email protected]",
  "through2"                   :                   "[email protected]",

  /*---------------------------------------------------------------*/
  /* fork of 0.2.14 allows passing parameters to main-bower-files. */
  /*---------------------------------------------------------------*/
  "bower-main"                 : "git+https://github.com/Pyo25/bower-main.git" 
  }

/*******************************************************************************
* run */
/**
* Executes <c>cmd</c> in the shell and calls <c>cb</c> on success. Error aborts.
* 
* Note: Error code -4082 is EBUSY error which is sometimes thrown by npm for 
* reasons unknown. Possibly this is due to antivirus program scanning the file 
* but it sometimes happens in cases where an antivirus program does not explain 
* it. The error generally will not happen a second time so this method will call 
* itself to try the command again if the EBUSY error occurs.
* 
* @param  cmd  Command to execute.
* @param  cb   Method to call on success. Text returned from stdout is input.
*******************************************************************************/
var run = function(cmd, cb)
  {
  /*---------------------------------------------*/
  /* Increase the maxBuffer to 10MB for commands */
  /* with a lot of output. This is not necessary */
  /* with spawn but it has other issues.         */
  /*---------------------------------------------*/
  exec(cmd, { maxBuffer: 1000*1024 }, function(err, stdout)
    {
    if      (!err)                   cb(stdout);
    else if (err.code | 0 == -4082) run(cmd, cb);
    else throw err;
    });
  };

/*******************************************************************************
* runCommand */
/**
* Logs the command and calls <c>run</c>.
*******************************************************************************/
var runCommand = function(cmd, cb)
  {
  console.log(cmd);
  run(cmd, cb);
  }

/*******************************************************************************
* Main line
*******************************************************************************/
var doLinks  = (process.argv[2] || "").toLowerCase() == 'links';
var names    = Object.keys(packages);
var name;
var installed;
var links;

/*------------------------------------------*/
/* Get the list of installed packages for   */
/* version comparison and install packages. */
/*------------------------------------------*/
console.log('Configuring global Node environment...')
run('npm ls -g --json', function(stdout)
  {
  installed = JSON.parse(stdout).dependencies || {};
  doWhile();
  });

/*--------------------------------------------*/
/* Start of asynchronous package installation */
/* loop. Do until all packages installed.     */
/*--------------------------------------------*/
var doWhile = function()
  {
  if (name = names.shift())
    doWhile0();
  }

var doWhile0 = function()
  {
  /*----------------------------------------------*/
  /* Installed package specification comes from   */
  /* 'from' field of installed packages. Required */
  /* specification comes from the packages list.  */
  /*----------------------------------------------*/
  var current  = (installed[name] || {}).from;
  var required =   packages[name];

  /*---------------------------------------*/
  /* Install the package if not installed. */
  /*---------------------------------------*/
  if (!current)
    runCommand('npm install -g '+required, doWhile1);

  /*------------------------------------*/
  /* If the installed version does not  */
  /* match, uninstall and then install. */
  /*------------------------------------*/
  else if (current != required)
    {
    delete installed[name];
    runCommand('npm remove -g '+name, function() 
      {
      runCommand('npm remove '+name, doWhile0);
      });
    }

  /*------------------------------------*/
  /* Skip package if already installed. */
  /*------------------------------------*/
  else
    doWhile1();
  };

var doWhile1 = function()
  {
  /*-------------------------------------------------------*/
  /* Create link to global package from local environment. */
  /*-------------------------------------------------------*/
  if (doLinks && !fs.existsSync(path.join('node_modules', name)))
    runCommand('npm link '+name, doWhile);
  else
    doWhile();
  };

现在,如果我想为我们的开发人员更新全局工具,我会更新“packages”对象并签入新脚本。我的开发人员检查了它,然后使用“node npm-setup.js”运行它,或者通过任何正在开发的产品中的“npm install”运行它以更新全局环境。整个过程需要5分钟。

此外,要为新开发人员配置环境,他们必须首先仅安装适用于 Windows 的 NodeJS 和 GIT,重新启动计算机,检查“共享文件”文件夹和任何正在开发的产品,然后开始工作。

.NET 产品的“package.json”在安装之前调用此脚本:

{ 
"name"                    : "Books",
"description"             : "Node (npm) configuration for Books Database Web Application Tools",
"version"                 : "2.1.1",
"private"                 : true,
"scripts":
  {
  "preinstall"            : "node ../../SharedFiles/npm-setup.js links",
  "postinstall"           : "bower install"
  },
"dependencies": {}
}

注释

  • 请注意,即使在 Windows 中,脚本引用也需要正斜杠
    环境。

  • “npm ls”将为所有包提供“npm ERR! extraneous:”消息
    本地链接,因为它们未在“package.json”中列出
    “依赖关系”。

编辑 1/29/16

上面更新的 npm-setup.js 脚本已修改如下:

  • var 包中的包“version” code> 现在是在命令行上传递给 npm install 的“package”值。此更改已更改为允许从注册存储库以外的位置安装软件包。

  • 如果该软件包已安装但不是所请求的软件包,则删除现有软件包并安装正确的软件包。

  • 出于未知原因,npm 在执行安装或链接时会定期抛出 EBUSY 错误 (-4082)。该错误被捕获并重新执行命令。该错误很少发生第二次,并且似乎总是会消失。

This is a bit old but I ran into the requirement so here is the solution I came up with.

The Problem:

Our development team maintains many .NET web application products we are migrating to AngularJS/Bootstrap. VS2010 does not lend itself easily to custom build processes and my developers are routinely working on multiple releases of our products. Our VCS is Subversion (I know, I know. I'm trying to move to Git but my pesky marketing staff is so demanding) and a single VS solution will include several separate projects. I needed my staff to have a common method for initializing their development environment without having to install the same Node packages (gulp, bower, etc.) several times on the same machine.

TL;DR:

  1. Need "npm install" to install the global Node/Bower development environment as well as all locally required packages for a .NET product.

  2. Global packages should be installed only if not already installed.

  3. Local links to global packages must be created automatically.

The Solution:

We already have a common development framework shared by all developers and all products so I created a NodeJS script to install the global packages when needed and create the local links. The script resides in "....\SharedFiles" relative to the product base folder:

/*******************************************************************************
* $Id: npm-setup.js 12785 2016-01-29 16:34:49Z sthames $
* ==============================================================================
* Parameters: 'links' - Create links in local environment, optional.
* 
* <p>NodeJS script to install common development environment packages in global
* environment. <c>packages</c> object contains list of packages to install.</p>
* 
* <p>Including 'links' creates links in local environment to global packages.</p>
* 
* <p><b>npm ls -g --json</b> command is run to provide the current list of 
* global packages for comparison to required packages. Packages are installed 
* only if not installed. If the package is installed but is not the required 
* package version, the existing package is removed and the required package is 
* installed.</p>.
*
* <p>When provided as a "preinstall" script in a "package.json" file, the "npm
* install" command calls this to verify global dependencies are installed.</p>
*******************************************************************************/
var exec = require('child_process').exec;
var fs   = require('fs');
var path = require('path');

/*---------------------------------------------------------------*/
/* List of packages to install and 'from' value to pass to 'npm  */
/* install'. Value must match the 'from' field in 'npm ls -json' */
/* so this script will recognize a package is already installed. */
/*---------------------------------------------------------------*/
var packages = 
  {
  "bower"                      :                      "[email protected]", 
  "event-stream"               :               "[email protected]",
  "gulp"                       :                       "[email protected]",
  "gulp-angular-templatecache" : "[email protected]",
  "gulp-clean"                 :                 "[email protected]", 
  "gulp-concat"                :                "[email protected]",
  "gulp-debug"                 :                 "[email protected]",
  "gulp-filter"                :                "[email protected]",
  "gulp-grep-contents"         :         "[email protected]",
  "gulp-if"                    :                    "[email protected]", 
  "gulp-inject"                :                "[email protected]", 
  "gulp-minify-css"            :            "[email protected]",
  "gulp-minify-html"           :           "[email protected]",
  "gulp-minify-inline"         :         "[email protected]",
  "gulp-ng-annotate"           :           "[email protected]",
  "gulp-processhtml"           :           "[email protected]",
  "gulp-rev"                   :                   "[email protected]",
  "gulp-rev-replace"           :           "[email protected]",
  "gulp-uglify"                :                "[email protected]",
  "gulp-useref"                :                "[email protected]",
  "gulp-util"                  :                  "[email protected]",
  "lazypipe"                   :                   "[email protected]",
  "q"                          :                          "[email protected]",
  "through2"                   :                   "[email protected]",

  /*---------------------------------------------------------------*/
  /* fork of 0.2.14 allows passing parameters to main-bower-files. */
  /*---------------------------------------------------------------*/
  "bower-main"                 : "git+https://github.com/Pyo25/bower-main.git" 
  }

/*******************************************************************************
* run */
/**
* Executes <c>cmd</c> in the shell and calls <c>cb</c> on success. Error aborts.
* 
* Note: Error code -4082 is EBUSY error which is sometimes thrown by npm for 
* reasons unknown. Possibly this is due to antivirus program scanning the file 
* but it sometimes happens in cases where an antivirus program does not explain 
* it. The error generally will not happen a second time so this method will call 
* itself to try the command again if the EBUSY error occurs.
* 
* @param  cmd  Command to execute.
* @param  cb   Method to call on success. Text returned from stdout is input.
*******************************************************************************/
var run = function(cmd, cb)
  {
  /*---------------------------------------------*/
  /* Increase the maxBuffer to 10MB for commands */
  /* with a lot of output. This is not necessary */
  /* with spawn but it has other issues.         */
  /*---------------------------------------------*/
  exec(cmd, { maxBuffer: 1000*1024 }, function(err, stdout)
    {
    if      (!err)                   cb(stdout);
    else if (err.code | 0 == -4082) run(cmd, cb);
    else throw err;
    });
  };

/*******************************************************************************
* runCommand */
/**
* Logs the command and calls <c>run</c>.
*******************************************************************************/
var runCommand = function(cmd, cb)
  {
  console.log(cmd);
  run(cmd, cb);
  }

/*******************************************************************************
* Main line
*******************************************************************************/
var doLinks  = (process.argv[2] || "").toLowerCase() == 'links';
var names    = Object.keys(packages);
var name;
var installed;
var links;

/*------------------------------------------*/
/* Get the list of installed packages for   */
/* version comparison and install packages. */
/*------------------------------------------*/
console.log('Configuring global Node environment...')
run('npm ls -g --json', function(stdout)
  {
  installed = JSON.parse(stdout).dependencies || {};
  doWhile();
  });

/*--------------------------------------------*/
/* Start of asynchronous package installation */
/* loop. Do until all packages installed.     */
/*--------------------------------------------*/
var doWhile = function()
  {
  if (name = names.shift())
    doWhile0();
  }

var doWhile0 = function()
  {
  /*----------------------------------------------*/
  /* Installed package specification comes from   */
  /* 'from' field of installed packages. Required */
  /* specification comes from the packages list.  */
  /*----------------------------------------------*/
  var current  = (installed[name] || {}).from;
  var required =   packages[name];

  /*---------------------------------------*/
  /* Install the package if not installed. */
  /*---------------------------------------*/
  if (!current)
    runCommand('npm install -g '+required, doWhile1);

  /*------------------------------------*/
  /* If the installed version does not  */
  /* match, uninstall and then install. */
  /*------------------------------------*/
  else if (current != required)
    {
    delete installed[name];
    runCommand('npm remove -g '+name, function() 
      {
      runCommand('npm remove '+name, doWhile0);
      });
    }

  /*------------------------------------*/
  /* Skip package if already installed. */
  /*------------------------------------*/
  else
    doWhile1();
  };

var doWhile1 = function()
  {
  /*-------------------------------------------------------*/
  /* Create link to global package from local environment. */
  /*-------------------------------------------------------*/
  if (doLinks && !fs.existsSync(path.join('node_modules', name)))
    runCommand('npm link '+name, doWhile);
  else
    doWhile();
  };

Now if I want to update a global tool for our developers, I update the "packages" object and check in the new script. My developers check it out and either run it with "node npm-setup.js" or by "npm install" from any of the products under development to update the global environment. The whole thing takes 5 minutes.

In addition, to configure the environment for the a new developer, they must first only install NodeJS and GIT for Windows, reboot their computer, check out the "Shared Files" folder and any products under development, and start working.

The "package.json" for the .NET product calls this script prior to install:

{ 
"name"                    : "Books",
"description"             : "Node (npm) configuration for Books Database Web Application Tools",
"version"                 : "2.1.1",
"private"                 : true,
"scripts":
  {
  "preinstall"            : "node ../../SharedFiles/npm-setup.js links",
  "postinstall"           : "bower install"
  },
"dependencies": {}
}

Notes

  • Note the script reference requires forward slashes even in a Windows
    environment.

  • "npm ls" will give "npm ERR! extraneous:" messages for all packages
    locally linked because they are not listed in the "package.json"
    "dependencies".

Edit 1/29/16

The updated npm-setup.js script above has been modified as follows:

  • Package "version" in var packages is now the "package" value passed to npm install on the command line. This was changed to allow for installing packages from somewhere other than the registered repository.

  • If the package is already installed but is not the one requested, the existing package is removed and the correct one installed.

  • For reasons unknown, npm will periodically throw an EBUSY error (-4082) when performing an install or link. This error is trapped and the command re-executed. The error rarely happens a second time and seems to always clear up.

め可乐爱微笑 2024-11-23 22:58:03

您可以使用单独的文件,例如 npm_globals.txt,而不是 package.json。该文件将在新行中包含每个模块,如下所示,

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

然后在命令行中运行,

< npm_globals.txt xargs npm install -g

检查它们是否正确安装,

npm list -g --depth=0

至于您是否应该这样做,我认为这完全取决于用例。对于大多数项目来说,这是没有必要的;最好让项目的 package.json 将这些工具和依赖项封装在一起。

但现在我发现当我跳上新机器时,我总是在全局安装 create-react-app 和其他 CLI。当版本控制不太重要时,有一种简单的方法来安装全局工具及其依赖项真是太好了。

现在,我正在使用 npx, npm 包运行程序,而不是全局安装包。

You could use a separate file, like npm_globals.txt, instead of package.json. This file would contain each module on a new line like this,

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Then in the command line run,

< npm_globals.txt xargs npm install -g

Check that they installed properly with,

npm list -g --depth=0

As for whether you should do this or not, I think it all depends on use case. For most projects, this isn't necessary; and having your project's package.json encapsulate these tools and dependencies together is much preferred.

But nowadays I find that I'm always installing create-react-app and other CLI's globally when I jump on a new machine. It's nice to have an easy way to install a global tool and its dependencies when versioning doesn't matter much.

And nowadays, I'm using npx, an npm package runner, instead of installing packages globally.

长发绾君心 2024-11-23 22:58:03

构建您自己的脚本来安装全局依赖项。这并不需要太多。 package.json 具有很强的可扩展性。

const { execSync } = require('child_process');
const fs = require('fs');

const package = JSON.parse(fs.readFileSync('package.json'));

let keys = Object.keys(package.dependencies);
let values = Object.values(package.dependencies);


for (let index = 0; index < keys.length; index++) {
    const key = keys[index];
    let value = values[index].replace("~", "").replace("^", "");

    console.log(`Installing: ${key}@${value} globally`,);
    execSync('npm i -g ' + `${key}@${value}`);
}

使用上面的内容,您甚至可以将其内联,如下!

看下面的 preinstall:

{
  "name": "Project Name",
  "version": "0.1.0",
  "description": "Project Description",
  "main": "app.js",
  "scripts": {
    "preinstall": "node -e \"const {execSync} = require('child_process'); JSON.parse(fs.readFileSync('package.json')).globalDependencies.forEach(globaldep => execSync('npm i -g ' + globaldep));\"",
    "build": "your transpile/compile script",
    "start": "node app.js",
    "test": "./node_modules/.bin/mocha --reporter spec",
    "patch-release": "npm version patch && npm publish && git add . && git commit -m \"auto-commit\" && git push --follow-tags"
  },
  "dependencies": [
  },
  "globalDependencies": [
    "[email protected]",
    "ionic",
    "potato"
  ],
  "author": "author",
  "license": "MIT",
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^5.2.0"
  },
  "bin": {
    "app": "app.js"
  }
}

node 的作者可能不承认 package.json 是一个项目文件。但确实如此。

Build your own script to install global dependencies. It doesn't take much. package.json is quite expandable.

const { execSync } = require('child_process');
const fs = require('fs');

const package = JSON.parse(fs.readFileSync('package.json'));

let keys = Object.keys(package.dependencies);
let values = Object.values(package.dependencies);


for (let index = 0; index < keys.length; index++) {
    const key = keys[index];
    let value = values[index].replace("~", "").replace("^", "");

    console.log(`Installing: ${key}@${value} globally`,);
    execSync('npm i -g ' + `${key}@${value}`);
}

Using the above, you can even make it inline, below!

Look at preinstall below:

{
  "name": "Project Name",
  "version": "0.1.0",
  "description": "Project Description",
  "main": "app.js",
  "scripts": {
    "preinstall": "node -e \"const {execSync} = require('child_process'); JSON.parse(fs.readFileSync('package.json')).globalDependencies.forEach(globaldep => execSync('npm i -g ' + globaldep));\"",
    "build": "your transpile/compile script",
    "start": "node app.js",
    "test": "./node_modules/.bin/mocha --reporter spec",
    "patch-release": "npm version patch && npm publish && git add . && git commit -m \"auto-commit\" && git push --follow-tags"
  },
  "dependencies": [
  },
  "globalDependencies": [
    "[email protected]",
    "ionic",
    "potato"
  ],
  "author": "author",
  "license": "MIT",
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^5.2.0"
  },
  "bin": {
    "app": "app.js"
  }
}

The authors of node may not admit package.json is a project file. But it is.

心病无药医 2024-11-23 22:58:03

package.json 中的所有模块都安装到 ./node_modules/

我找不到明确说明的内容,但这是 NPM

All modules from package.json are installed to ./node_modules/

I couldn't find this explicitly stated but this is the package.json reference for NPM.

寻找一个思念的角度 2024-11-23 22:58:03

这可能是生产中出现问题的原因。
如果项目依赖项安装在项目文件夹之外,则如果其他人删除或替换您的包或更改文件夹权限,则代码可能会损坏。

将所有内容放在一个文件夹中会更耐用,并使系统可预测,维护任务也更容易。

This probably may be door for problems in production.
if project dependencies installed outside project folder, the code may break if anybody else delete or replace your packages or change folder permissions.

Having every thing in one folder is more durable and make system predictable and maintenance tasks easier.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文