Npm i save что это

от admin

npm-install

This command installs a package and any packages that it depends on. If the package has a package-lock, or an npm shrinkwrap file, or a yarn lock file, the installation of dependencies will be driven by that, respecting the following order of precedence:

  • npm-shrinkwrap.json
  • package-lock.json
  • yarn.lock
  • a) a folder containing a program described by a package.json file
  • b) a gzipped tarball containing (a)
  • c) a url that resolves to (b)
  • d) a <name>@<version> that is published on the registry (see registry ) with (c)
  • e) a <name>@<tag> (see npm dist-tag ) that points to (d)
  • f) a <name> that has a "latest" tag satisfying (e)
  • g) a <git remote url> that resolves to (a)

Even if you never publish your package, you can still get a lot of benefits of using npm if you just want to write a node program (a), and perhaps if you also want to be able to easily install it elsewhere after packing it up into a tarball (b).

npm install (in a package directory, no arguments):

Install the dependencies to the local node_modules folder.

In global mode (ie, with -g or —global appended to the command), it installs the current package context (ie, the current working directory) as a global package.

By default, npm install will install all modules listed as dependencies in package.json .

With the —production flag (or when the NODE_ENV environment variable is set to production ), npm will not install modules listed in devDependencies . To install all modules listed in both dependencies and devDependencies when NODE_ENV environment variable is set to production , you can use —production=false .

NOTE: The —production flag has no particular meaning when adding a dependency to a project.

npm install <folder> :

If <folder> sits inside the root of your project, its dependencies will be installed and may be hoisted to the top-level node_modules as they would for other types of dependencies. If <folder> sits outside the root of your project, npm will not install the package dependencies in the directory <folder> , but it will create a symlink to <folder> .

NOTE: If you want to install the content of a directory like a package from the registry instead of creating a link, you would need to use the —install-links option.

npm install <tarball file> :

Install a package that is sitting on the filesystem. Note: if you just want to link a dev directory into your npm root, you can do this more easily by using npm link .

The filename must use .tar , .tar.gz , or .tgz as the extension.

The package contents should reside in a subfolder inside the tarball (usually it is called package/ ). npm strips one directory layer when installing the package (an equivalent of tar x —strip-components=1 is run).

The package must contain a package.json file with name and version properties.

npm install <tarball url> :

Fetch the tarball url, and then install it. In order to distinguish between this and other options, the argument must start with "http://" or "https://"

Do a <name>@<tag> install, where <tag> is the "tag" config. (See config . The config's default value is latest .)

In most cases, this will install the version of the modules tagged as latest on the npm registry.

npm install saves any specified packages into dependencies by default. Additionally, you can control where and how they get saved with some additional flags:

-P, —save-prod : Package will appear in your dependencies . This is the default unless -D or -O are present.

-D, —save-dev : Package will appear in your devDependencies .

-O, —save-optional : Package will appear in your optionalDependencies .

—no-save : Prevents saving to dependencies .

When using any of the above options to save dependencies to your package.json, there are two additional, optional flags:

-E, —save-exact : Saved dependencies will be configured with an exact version rather than using npm's default semver range operator.

-B, —save-bundle : Saved dependencies will also be added to your bundleDependencies list.

Further, if you have an npm-shrinkwrap.json or package-lock.json then it will be updated as well.

<scope> is optional. The package will be downloaded from the registry associated with the specified scope. If no registry is associated with the given scope the default registry is assumed. See scope .

Note: if you do not include the @-symbol on your scope name, npm will interpret this as a GitHub repository instead, see below. Scopes names must also be followed by a slash.

Note: If there is a file or folder named <name> in the current working directory, then it will try to install that, and only try to fetch the package by name if it is not valid.

npm install <alias>@npm:<name> :

Install a package under a custom alias. Allows multiple versions of a same-name package side-by-side, more convenient import names for packages with otherwise long ones, and using git forks replacements or forked npm packages as replacements. Aliasing works only on your project and does not rename packages in transitive dependencies. Aliases should follow the naming conventions stated in validate-npm-package-name .

Install the version of the package that is referenced by the specified tag. If the tag does not exist in the registry data for that package, then this will fail.

Install the specified version of the package. This will fail if the version has not been published to the registry.

npm install [<@scope>/]<name>@<version range> :

Install a version of the package matching the specified version range. This will follow the same rules for resolving dependencies described in package.json .

Note that most version ranges must be put in quotes so that your shell will treat it as a single argument.

npm install <git remote url> :

Installs the package from the hosted git provider, cloning it with git . For a full git remote url, only that URL will be attempted.

<protocol> is one of git , git+ssh , git+http , git+https , or git+file .

If #<commit-ish> is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:<semver> , <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then the default branch of the repository is used.

If the repository makes use of submodules, those submodules will be cloned as well.

If the package being installed contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed.

The following git environment variables are recognized by npm and will be added to the environment when running git:

See the git man page for details.

npm install <githubname>/<githubrepo>[#<commit-ish>] :

npm install github:<githubname>/<githubrepo>[#<commit-ish>] :

Install the package at https://github.com/githubname/githubrepo by attempting to clone it using git .

If #<commit-ish> is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:<semver> , <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then the default branch is used.

As with regular git dependencies, dependencies and devDependencies will be installed if the package has a prepare script before the package is done installing.

npm install gist:[<githubname>/]<gistID>[#<commit-ish>|#semver:<semver>] :

Install the package at https://gist.github.com/gistID by attempting to clone it using git . The GitHub username associated with the gist is optional and will not be saved in package.json .

As with regular git dependencies, dependencies and devDependencies will be installed if the package has a prepare script before the package is done installing.

npm install bitbucket:<bitbucketname>/<bitbucketrepo>[#<commit-ish>] :

Install the package at https://bitbucket.org/bitbucketname/bitbucketrepo by attempting to clone it using git .

If #<commit-ish> is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:<semver> , <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then master is used.

As with regular git dependencies, dependencies and devDependencies will be installed if the package has a prepare script before the package is done installing.

npm install gitlab:<gitlabname>/<gitlabrepo>[#<commit-ish>] :

Install the package at https://gitlab.com/gitlabname/gitlabrepo by attempting to clone it using git .

If #<commit-ish> is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:<semver> , <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then master is used.

As with regular git dependencies, dependencies and devDependencies will be installed if the package has a prepare script before the package is done installing.

You may combine multiple arguments and even multiple types of arguments. For example:

The —tag argument will apply to all of the specified install targets. If a tag with the given name exists, the tagged version is preferred over newer versions.

The —dry-run argument will report in the usual way what the install would have done without actually installing anything.

The —package-lock-only argument will only update the package-lock.json , instead of checking node_modules and downloading dependencies.

The -f or —force argument will force npm to fetch remote resources even if a local copy exists on disk.

See the config help doc. Many of the configuration params have some effect on installation, since that's most of what npm does.

These are some of the most common options related to installation.

  • Default: true unless when using npm update where it defaults to false
  • Type: Boolean

Save installed packages to a package.json file as dependencies.

When used with the npm rm command, removes the dependency from package.json .

Will also prevent writing to package-lock.json if set to false .

  • Default: false
  • Type: Boolean

Dependencies saved to package.json will be configured with an exact version rather than using npm's default semver range operator.

  • Default: false
  • Type: Boolean

Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See folders for more on the differences in behavior.

  • packages are installed into the /lib/node_modules folder, instead of the current working directory.
  • bin files are linked to /bin
  • man pages are linked to /share/man
  • Default: false
  • Type: Boolean

Causes npm to install the package into your local node_modules folder with the same layout it uses with the global node_modules folder. Only your direct dependencies will show in node_modules and everything they depend on will be flattened in their node_modules folders. This obviously will eliminate some deduping. If used with legacy-bundling , legacy-bundling will be preferred.

  • Default: false
  • Type: Boolean

Causes npm to install the package such that versions of npm prior to 1.4, such as the one included with node 0.8, can install the package. This eliminates all automatic deduping. If used with global-style this option will be preferred.

  • Default: 'dev' if the NODE_ENV environment variable is set to 'production', otherwise empty.
  • Type: "dev", "optional", or "peer" (can be set multiple times)

Dependency types to omit from the installation tree on disk.

Note that these dependencies are still resolved and added to the package-lock.json or npm-shrinkwrap.json file. They are just not physically installed on disk.

If a package type appears in both the —include and —omit lists, then it will be included.

If the resulting omit list includes 'dev' , then the NODE_ENV environment variable will be set to 'production' for all lifecycle scripts.

  • Default: false
  • Type: Boolean

If set to true , and —legacy-peer-deps is not set, then any conflicting peerDependencies will be treated as an install failure, even if npm could reasonably guess the appropriate resolution based on non-peer dependency relationships.

By default, conflicting peerDependencies deep in the dependency graph will be resolved using the nearest non-peer dependency specification, even if doing so will result in some packages receiving a peer dependency outside the range set in their package's peerDependencies object.

When such and override is performed, a warning is printed, explaining the conflict and the packages involved. If —strict-peer-deps is set, then this warning is treated as a failure.

  • Default: true
  • Type: Boolean

If set to false, then ignore package-lock.json files when installing. This will also prevent writing package-lock.json if save is true.

This configuration does not affect npm ci .

  • Default: false
  • Type: Boolean

Run all build scripts (ie, preinstall , install , and postinstall ) scripts for installed packages in the foreground process, sharing standard input, output, and error with the main npm process.

Note that this will generally make installs run slower, and be much noisier, but can be useful for debugging.

  • Default: false
  • Type: Boolean

If true, npm does not run scripts specified in package.json files.

Note that commands explicitly intended to run a particular script, such as npm start , npm stop , npm restart , npm test , and npm run-script will still run their intended script if ignore-scripts is set, but they will not run any pre- or post-scripts.

  • Default: true
  • Type: Boolean

When "true" submit audit reports alongside the current npm command to the default registry and all registries configured for scopes. See the documentation for npm audit for details on what is submitted.

  • Default: true
  • Type: Boolean

Tells npm to create symlinks (or .cmd shims on Windows) for package executables.

Set to false to have it not do this. This can be used to work around the fact that some file systems don't support symlinks, even on ostensibly Unix systems.

  • Default: true
  • Type: Boolean

When "true" displays the message at the end of each npm install acknowledging the number of dependencies looking for funding. See npm fund for details.

  • Default: false
  • Type: Boolean

Indicates that you don't want npm to make any changes and that it should only report what it would have done. This can be passed into any of the commands that modify your local installation, eg, install , update , dedupe , uninstall , as well as pack and publish .

Note: This is NOT honored by other network related commands, eg dist-tags , owner , etc.

  • Default:
  • Type: String (can be set multiple times)

Enable running a command in the context of the configured workspaces of the current project while filtering by running only the workspaces defined by this configuration option.

Valid values for the workspace config are either:

  • Workspace names
  • Path to a workspace directory
  • Path to a parent workspace directory (will result in selecting all workspaces within that folder)

When set for the npm init command, this may be set to the folder of a workspace which does not yet exist, to create the folder and set it up as a brand new workspace within the project.

This value is not exported to the environment for child processes.

  • Default: null
  • Type: null or Boolean

Set to true to run the command in the context of all configured workspaces.

Explicitly setting this to false will cause commands like install to ignore workspaces altogether. When not set explicitly:

  • Commands that operate on the node_modules tree (install, update, etc.) will link workspaces into the node_modules folder. — Commands that do other things (test, exec, publish, etc.) will operate on the root project, unless one or more workspaces are specified in the workspace config.

This value is not exported to the environment for child processes.

  • Default: false
  • Type: Boolean

Include the workspace root when workspaces are enabled for a command.

When false, specifying individual workspaces via the workspace config, or all workspaces via the workspaces flag, will cause npm to operate only on the specified workspaces, and not on the root project.

This value is not exported to the environment for child processes.

  • Default: false
  • Type: Boolean

When set file: protocol dependencies that exist outside of the project root will be packed and installed as regular dependencies instead of creating a symlink. This option has no effect on workspaces.

Given a package structure: A, B, C , the npm install algorithm produces:

That is, the dependency from B to C is satisfied by the fact that A already caused C to be installed at a higher level. D is still installed at the top level because nothing conflicts with it.

For A, B, C , this algorithm produces:

Because B's D@1 will be installed in the top-level, C now has to install D@2 privately for itself. This algorithm is deterministic, but different trees may be produced if two dependencies are requested for installation in a different order.

See folders for a more detailed description of the specific folder structures that npm creates.

Npm i save что это

Node Package Manager (npm) provides following two main functionalities: Online repositories for node.js packages/modules which are searchable on search.nodejs.org. Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.

# Installing packages

# Introduction

Package is a term used by npm to denote tools that developers can use for their projects. This includes everything from libraries and frameworks such as jQuery and AngularJS to task runners such as Gulp.js. The packages will come in a folder typically called node_modules , which will also contain a package.json file. This file contains information regarding all the packages including any dependencies, which are additional modules needed to use a particular package.

Npm uses the command line to both install and manage packages, so users attempting to use npm should be familiar with basic commands on their operating system i.e.: traversing directories as well as being able to see the contents of directories.

# Installing NPM

Note that in order to install packages, you must have NPM installed.

The recommended way to install NPM is to use one of the installers from the Node.js download page

(opens new window) . You can check to see if you already have node.js installed by running either the npm -v or the npm version command.

After installing NPM via the Node.js installer, be sure to check for updates. This is because NPM gets updated more frequently than the Node.js installer. To check for updates run the following command:

# How to install packages

To install one or more packages use the following:

Note: This will install the package in the directory that the command line is currently in, thus it is important to check whether the appropriate directory has been chosen

If you already have a package.json file in your current working directory and dependencies are defined in it, then npm install will automatically resolve and install all dependencies listed in the file. You can also use the shorthand version of the npm install command which is: npm i

If you want to install a specific version of a package use:

If you want to install a version which matches a specific version range use:

If you want to install the latest version use:

The above commands will search for packages in the central npm repository at npmjs.com

(opens new window) . If you are not looking to install from the npm registry, other options are supported, such as:

Usually, modules will be installed locally in a folder named node_modules , which can be found in your current working directory. This is the directory require() will use to load modules in order to make them available to you.

If you already created a package.json file, you can use the —save (shorthand -S ) option or one of its variants to automatically add the installed package to your package.json as a dependency. If someone else installs your package, npm will automatically read dependencies from the package.json file and install the listed versions. Note that you can still add and manage your dependencies by editing the file later, so it’s usually a good idea to keep track of dependencies, for example using:

In order to install packages and save them only if they are needed for development, not for running them, not if they are needed for the application to run, follow the following command:

# Installing dependencies

Some modules do not only provide a library for you to use, but they also provide one or more binaries which are intended to be used via the command line. Although you can still install those packages locally, it is often preferred to install them globally so the command-line tools can be enabled. In that case, npm will automatically link the binaries to appropriate paths (e.g. /usr/local/bin/<name> ) so they can be used from the command line. To install a package globally, use:

If you want to see a list of all the installed packages and their associated versions in the current workspace, use:

Adding an optional name argument can check the version of a specific package.

Note: If you run into permission issues while trying to install an npm module globally, resist the temptation to issue a sudo npm install -g . to overcome the issue. Granting third-party scripts to run on your system with elevated privileges is dangerous. The permission issue might mean that you have an issue with the way npm itself was installed. If you’re interested in installing Node in sandboxed user environments, you might want to try using nvm

If you have build tools, or other development-only dependencies (e.g. Grunt), you might not want to have them bundled with the application you deploy. If that’s the case, you’ll want to have it as a development dependency, which is listed in the package.json under devDependencies . To install a package as a development-only dependency, use —save-dev (or -D ).

You will see that the package is then added to the devDependencies of your package.json .

To install dependencies of a downloaded/cloned node.js project, you can simply use

npm will automatically read the dependencies from package.json and install them.

# NPM Behind A Proxy Server

If your internet access is through a proxy server, you might need to modify npm install commands that access remote repositories. npm uses a configuration file which can be updated via command line:

You can locate your proxy settings from your browser’s settings panel. Once you have obtained the proxy settings (server URL, port, username and password); you need to configure your npm configurations as follows.

username , password , port fields are optional. Once you have set these, your npm install , npm i -g etc. would work properly.

# Uninstalling packages

To uninstall one or more locally installed packages, use:

The uninstall command for npm has five aliases that can also be used:

If you would like to remove the package from the package.json file as part of the uninstallation, use the —save flag (shorthand: -S ):

For a development dependency, use the —save-dev flag (shorthand: -D ):

For an optional dependency, use the —save-optional flag (shorthand: -O ):

For packages that are installed globally use the —global flag (shorthand: -g ):

# Setting up a package configuration

Node.js package configurations are contained in a file called package.json that you can find at the root of each project. You can setup a brand new configuration file by calling:

That will try to read the current working directory for Git repository information (if it exists) and environment variables to try and autocomplete some of the placeholder values for you. Otherwise, it will provide an input dialog for the basic options.

If you’d like to create a package.json with default values use:

If you’re creating a package.json for a project that you are not going to be publishing as an npm package (i.e. solely for the purpose of rounding up your dependencies), you can convey this intent in your package.json file:

  1. Optionally set the private property to true to prevent accidental publishing.
  2. Optionally set the license property to "UNLICENSED" to deny others the right to use your package.

To install a package and automatically save it to your package.json , use:

The package and associated metadata (such as the package version) will appear in your dependencies. If you save if as a development dependency (using —save-dev ), the package will instead appear in your devDependencies .

With this bare-bones package.json , you will encounter warning messages when installing or upgrading packages, telling you that you are missing a description and the repository field. While it is safe to ignore these messages, you can get rid of them by opening the package.json in any text editor and adding the following lines to the JSON object:

# Running scripts

You may define scripts in your package.json , for example:

To run the echo script, run npm run echo from the command line. Arbitrary scripts, such as echo above, have to be be run with npm run <script name> . npm also has a number of official scripts that it runs at certain stages of the package’s life (like preinstall ). See here

(opens new window) for the entire overview of how npm handles script fields.

npm scripts are used most often for things like starting a server, building the project, and running tests. Here’s a more realistic example:

In the scripts entries, command-line programs like mocha will work when installed either globally or locally. If the command-line entry does not exist in the system PATH, npm will also check your locally installed packages.

If your scripts become very long, they can be split into parts, like this:

# Basic semantic versioning

Before publishing a package you have to version it. npm supports semantic versioning

(opens new window) , this means there are patch, minor and major releases.

For example, if your package is at version 1.2.3 to change version you have to:

  1. patch release: npm version patch => 1.2.4
  2. minor release: npm version minor => 1.3.0
  3. major release: npm version major => 2.0.0

You can also specify a version directly with:

npm version 3.1.4 => 3.1.4

When you set a package version using one of the npm commands above, npm will modify the version field of the package.json file, commit it, and also create a new Git tag with the version prefixed with a "v", as if you’ve issued the command:

Unlike other package managers like Bower, the npm registry doesn’t rely on Git tags being created for every version. But, if you like using tags, you should remember to push the newly created tag after bumping the package version:

git push origin master (to push the change to package.json)

git push origin v3.1.4 (to push the new tag)

Or you can do this in one swoop with:

git push origin master —tags

# Publishing a package

First, make sure that you have configured your package (as said in Setting up a package configuration

(opens new window) ​). Then, you have to be logged in to npmjs.

If you already have a npm user

If you don’t have a user

To check that your user is registered in the current client

After that, when your package is ready to be published use

And you are done.

If you need to publish a new version, ensure that you update your package version, as stated in Basic semantic versioning

(opens new window) . Otherwise, npm will not let you publish the package.

# Removing extraneous packages

To remove extraneous packages (packages that are installed but not in dependency list) run the following command:

To remove all dev packages add —production flag:

# Scopes and repositories

If the name of your own package starts with @myscope and the scope "myscope" is associated with a different repository, npm publish will upload your package to that repository instead.

You can also persist these settings in a .npmrc file:

This is useful when automating the build on a CI server f.e.

# Listing currently installed packages

To generate a list (tree view) of currently installed packages, use

ls, la and ll are aliases of list command. la and ll commands shows extended information like description and repository.

Options

The response format can be changed by passing options.

  • json — Shows information in json format
  • long — Shows extended information
  • parseable — Shows parseable list instead of tree
  • global — Shows globally installed packages
  • depth — Maximum display depth of dependency tree
  • dev/development — Shows devDependencies
  • prod/production — Shows dependencies

If you want, you can also go to the package’s home page.

# Updating npm and packages

Since npm itself is a Node.js module, it can be updated using itself.

If OS is Windows must be running command prompt as Admin

If you want to check for updated versions you can do:

In order to update a specific package:

This will update the package to the latest version according to the restrictions in package.json

In case you also want to lock the updated version in package.json:

# Locking modules to specific versions

By default, npm installs the latest available version of modules according to each dependencies’ semantic version

(opens new window) . This can be problematic if a module author doesn’t adhere to semver and introduces breaking changes in a module update, for example.

To lock down each dependencies’ version (and the versions of their dependencies, etc) to the specific version installed locally in the node_modules folder, use

This will then create a npm-shrinkwrap.json alongside your package.json which lists the specific versions of dependancies.

# Setting up for globally installed packages

You can use npm install -g to install a package "globally." This is typically done to install an executable that you can add to your path to run. For example:

If you update your path, you can call gulp directly.

On many OSes, npm install -g will attempt to write to a directory that your user may not be able to write to such as /usr/bin . You should not use sudo npm install in this case since there is a possible security risk of running arbitrary scripts with sudo and the root user may create directories in your home that you cannot write to which makes future installations more difficult.

You can tell npm where to install global modules to via your configuration file,

/.npmrc . This is called the prefix which you can view with npm prefix .

This will use the prefix whenever you run npm install -g . You can also use npm install —prefix

/.npm-global-modules to set the prefix when you install. If the prefix is the same as your configuration, you don’t need to use -g .

In order to use the globally installed module, it needs to be on your path:

Now when you run npm install -g gulp-cli you will be able to use gulp .

Note: When you npm install (without -g ) the prefix will be the directory with package.json or the current directory if none is found in the hierarchy. This also creates a directory node_modules/.bin that has the executables. If you want to use an executable that is specific to a project, it’s not necessary to use npm install -g . You can use the one in node_modules/.bin .

# Linking projects for faster debugging and development

Building project dependencies can sometimes be a tedious task. Instead of publishing a package version to NPM and installing the dependency to test the changes, use npm link . npm link creates a symlink so the latest code can be tested in a local environment. This makes testing global tools and project dependencies easier by allowing the latest code run before making a published version.

# Help text

# Steps for linking project dependencies

When creating the dependency link, note that the package name is what is going to be referenced in the parent project.

  1. CD into a dependency directory (ex: cd ../my-dep )
  2. npm link
  3. CD into the project that is going to use the dependency
  4. npm link my-dep or if namespaced npm link @namespace/my-dep

# Steps for linking a global tool

  1. CD into the project directory (ex: cd eslint-watch )
  2. npm link
  3. Use the tool
  4. esw —quiet

# Problems that may arise

Linking projects can sometimes cause issues if the dependency or global tool is already installed. npm uninstall (-g) <pkg> and then running npm link normally resolves any issues that may arise.

What is the —save option for npm install?

As of npm 5.0.0, installed modules are added as a dependency by default, so the —save option is no longer needed. The other save options still exist and are listed in the documentation for npm install .

Before version 5, NPM simply installed a package under node_modules by default. When you were trying to install dependencies for your app/module, you would need to first install them, and then add them (along with the appropriate version number) to the dependencies section of your package.json .

The —save option instructed NPM to include the package inside of the dependencies section of your package.json automatically, thus saving you an additional step.

In addition, there are the complementary options —save-dev and —save-optional which save the package under devDependencies and optionalDependencies , respectively. This is useful when installing development-only packages, like grunt or your testing library.

Update as of npm 5:

As of npm 5.0.0 (released in May 2017), installed modules are added as a dependency by default, so the —save option is no longer needed.
The other save options still exist and are listed in the documentation for npm install .

To add package in dependencies:

To add package in devDependencies

package.json

Henke's user avatar

Joe L.'s user avatar

Update as of npm 5:

As of npm 5.0.0, installed modules are added as a dependency by default, so the —save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.

It won’t do anything if you don’t have a package.json file. Start by running npm init to create one. Then calls to npm install —save or npm install —save-dev or npm install —save-optional will update the package.json to list your dependencies.

Nick Retallack's user avatar

Enter image description here

So it seems that by running npm install package_name , the package dependency should be automatically added to package.json, right?

Peter Mortensen's user avatar

ROROROOROROR's user avatar

You can also use -S , -D or -P which are equivalent of saving the package to an application dependency, a development dependency or production dependency. See more NPM shortcuts below:

This list of shortcuts can be obtained by running the following command:

Peter Mortensen's user avatar

DevWL's user avatar

npm v6.x update

Now you can use one of npm i or npm i -S or npm i -P to install and save a module as a dependency.

npm i is the alias of npm install

  1. npm i is equal to npm install , meaning the default save module as a dependency;
  2. npm i -S is equal to npm install —save (npm v5-)
  3. npm i -P is equal to npm install —save-prod (npm v5+)

Check out your npm version

Get npm cli help information

Get npm install help

npm help install alias npm -h i

References

Enter image description here

Peter Mortensen's user avatar

xgqfrms's user avatar

npm install package_x —save

The given package (package_x) will be saved in file package.json inside dependencies.

npm install <<package_x>> —save-dev

then it will be saved inside devDependencies.

Peter Mortensen's user avatar

As of npm 5, it is more favorable to use —save-prod (or -P ) than —save but doing the same thing, as is stated in npm install. So far, —save still works if provided.

As of npm 5, npm will now save by default.

In case, if you would like npm to work in a similar old fashion (no autosave) to how it was working in previous versions, you can update the config option to enable autosave as below.

To get the current setting, you can execute the following command:

Peter Mortensen's user avatar

–npm install —save or -S: When the following command is used with npm install, this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give the desired results.

But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.

Peter Mortensen's user avatar

npm install —save or npm install —save-dev is why we choose one option between these two, while installing the package in our project.

Использование модулей Node.js с npm и package.json

Использование модулей Node.js с npm и package.json

Благодаря таким функциям, как оперативное выполнение ввода/вывода и его широко известному синтаксису JavaScript, Node.js быстро стал популярной рабочей средой для разработки веб-приложений на стороне сервера. Но по мере роста интереса создаются более крупные приложения, а управление сложностью базы кода и ее зависимостей становится сложнее. Node.js организует эти сложные процессы с помощью модулей, которые являются любым отдельным файлом JavaScript, содержащим функции или объекты, используемые другими программами или модулями. Группа из одного или нескольких модулей часто называется пакетом, а эти пакеты организованы менеджерами пакетов.

Менеджер пакетов Node.js (npm) — это стандартный и наиболее популярный менеджер пакетов в экосистеме Node.js; он преимущественно используется для установки и управления внешними модулями проекта Node.js. Он также часто используется для установки широкого спектра инструментов командной строки и запуска скриптов проекта. npm отслеживает модули, установленные в проекте с файлом package.json , находящимся в директории проекта и содержащим следующее:

  • Все модули, необходимые для проекта, и их установленные версии
  • Все метаданные для проекта — например, автор, лицензия и т. п.
  • Скрипты, которые можно запустить для автоматизации задач в проекте

При создании более сложных проектов Node.js управление своими метаданными и зависимостями при помощи файла package.json позволит обеспечить более предсказуемые сборки, поскольку все внешние зависимости одинаковы. Файл будет автоматически отслеживать эту информацию. Хотя вы можете изменять файл напрямую для обновления метаданных вашего проекта, вам будет редко требоваться взаимодействовать с ним напрямую для управления модулями.

В этом обучающем руководстве вы будете управлять пакетами с помощью npm. Первый шаг будет состоять в создании и понимании файла package.json . Затем вы сможете использовать его для отслеживания всех модулей, которые вы установили в вашем проекте. В заключение вы укажете зависимости пакетов, обновите пакеты, удалите пакеты и проведете проверку на предмет уязвимостей безопасности.

Предварительные требования

Для данного обучающего руководства вам потребуется следующее:

  • Node.js, установленный на вашем компьютере для разработки. В этом обучающем руководстве используется версия 10.17.0. Чтобы установить его в macOS или Ubuntu 18.04, следуйте указаниям руководства Установка Node.js и создание локальной среды разработки в macOS или раздела Установка с помощью PPA руководства Установка Node.js в Ubuntu 18.04. При установке Node.js также выполняется установка npm, в этом обучающем руководстве используется версия 6.11.3.

Шаг 1 — Создание файла package.json

Начнем это обучающее руководство с проекта в качестве примера — гипотетический модуль локатора Node.js, получающий IP-адрес пользователя и возвращающий страну происхождения. Вы не будете кодировать модуль в этом обучающем руководстве. Однако пакеты, которыми вы управляете, будут актуальны, если вы их разрабатывали.

Вначале вы создадите файл package.json , который будет содержать полезные метаданные проекта и поможет вам управлять зависимыми модулями Node.js проекта. Как следует из названия суффикса, это файл JSON (обозначение объектов JavaScript). JSON — стандартный формат, используемый для обмена, основанный на объектах JavaScript и состоящий из данных, сохраненных как пары «ключ-значение». Если хотите узнать больше о JSON, ознакомьтесь с нашей статьей Введение в JSON.

Поскольку файл package.json содержит многочисленные свойства, может быть затруднительно создавать его вручную без копирования и вставки шаблона из другого места. Чтобы упростить процесс, npm предоставляет команду init . Это интерактивная команда, которая задает ряд вопросов и создает файл package.json на основе ваших ответов.

Использование команды init

Вначале настройте проект, чтобы можно было попрактиковаться в управлении модулями. В своей оболочке создайте новую папку под названием locator :

Затем перейдите в новую папку:

Теперь инициализируйте интерактивную командную строку, введя следующее:

Примечание. Если ваш код будет использовать Git для контроля версий, сначала создайте репозиторий Git, а затем запустите npm init . Команда автоматически понимает, что она находится в папке, управляемой Git. Если задан удаленный Git, он автоматически заполняет следующие поля для вашего файла package.json : repository , bugs и homepage . Если вы инициализировали репозиторий после создания файла package.json , вам нужно будет добавить эту информацию самостоятельно. Дополнительную информацию по контролю версий Git можно найти в нашей серии Введение в Git: установка, использование и ответвления.

Результат будет выглядеть следующим образом:

Сначала вам будет предложено ввести имя нового проекта. По умолчанию команда предполагает, что это имя папки, в которой вы находитесь. Значения по умолчанию для каждого свойства показаны в скобках () . Поскольку в настоящем руководстве будет использоваться значение имени по умолчанию, нажмите ENTER , чтобы принять его.

Следующее значение, которое нужно ввести — версия . Как и в случае с именем , это поле требуется, если ваш проект будет размещаться вместе с другими проектами в репозитории пакетов npm.

Примечание. Пакеты Node.js должны соответствовать руководству по указанию версий Semantic (semver). Поэтому первое число будет номером версии MAJOR , который изменяется только при изменении API. Второе число будет номером версии MINOR , который изменяется при добавлении функций. Последнее число будет номером версии PATCH , который изменяется при исправлении ошибок.

Нажмите ENTER , чтобы принять версию по умолчанию.

Следующее поле описание — полезная строка, чтобы объяснить, что делает ваш модуль Node.js. Наш проект гипотетического локатора получит IP-адрес пользователя и выдаст страну происхождения. Подходящее описание : находит страну происхождения по входящему запросу , поэтому введите нечто подобное и нажмите ENTER . Описание очень полезно, когда люди ищут ваш модуль.

Следующая строка запросит у вас точку входа . Если кто-то осуществляет установку и нуждается в вашем модуле, то указанное вами в точке входа будет первой частью вашей загружаемой программы. Значение должно быть относительным местом расположения файла JavaScript и будет добавлено в свойство main файла package.json . Нажмите ENTER , чтобы сохранить значение по умолчанию.

Примечание. В большинстве модулей файл index.js является основной точкой входа. Это значение по умолчанию для свойства main файла package.json , которое представляет собой точку входа для модулей npm. Если не будет package.json , Node.js попробует загружать index.js по умолчанию.

Далее вам нужно будет ввести команду test , исполняемый скрипт или команду, чтобы запустить тесты проекта. Во многих популярных модулях Node.js тесты написаны и осуществляются с помощью Mocha, Jest, Jasmine или других тестовых структур. Поскольку тестирование выходит за рамки этой статьи, оставьте эту опцию пустой и нажмите ENTER , чтобы продолжить.

Затем команда init запросит репозиторий GitHub проекта. Вы не будете использовать его в данном примере, поэтому оставьте и его пустым.

После строки репозитория команда запросит ключевые слова . Это свойство представляет собой массив строк с полезными терминами, которые можно использовать для поиска репозитория. Лучше всего иметь небольшой набор слов, которые наиболее актуальны для вашего проекта, чтобы обеспечить более целенаправленный поиск. Введите эти ключевые слова как строку с запятыми, разделяющими каждое значение. Для данного проекта, служащего примером, введите ip,geo,country в командной строке. В готовом package.json будет три элемента в массиве для ключевых слов .

Следующее поле в командной строке — автор . Это полезно для пользователей вашего модуля, которые хотят связаться с вами. Например, если кто-то обнаружит средство эксплуатации уязвимостей в вашем модуле, они смогут использовать это поле, чтобы сообщить о проблеме, чтобы вы смогли ее исправить. Поле автор представляет собой строку в следующем формате: " Name \< Email \> ( Website )"​​​​​ ​. Например, "Sammy \<sammy@your_domain\> (https://your_domain)" — подходящее значение поля «автор». Электронная почта и веб-сайт являются опциональными данными — подходящее значение поля «автор» может состоять только из имени. Добавьте ваши контактные данные в качестве автора и подтвердите нажатием ENTER .

В заключение вам будет предложено ввести лицензию . Это определяет юридические разрешения и ограничения, которые будут у пользователей при использовании вашего модуля. Многие модули Node.js имеют открытый исходный код, поэтому npm задает значение ISC по умолчанию.

К этому моменту вы должны будете рассмотреть ваши опции лицензирования и определить, что подходит лучше всего для вашего проекта. Дополнительную информацию по различным видам открытых лицензий можно найти в этом списке лицензий от организации Open Source Initiative. Если вы не захотите предоставлять лицензию для частного репозитория, вы можете ввести UNLICENSED в командной строке. Для данного примера используйте лицензию ISC по умолчанию и нажмите ENTER , чтобы завершить этот процесс.

Теперь команда init отобразит файл package.json , который она будет создавать. Он будет выглядеть примерно так:

Когда информация совпадет с тем, что вы видите здесь, нажмите ENTER , чтобы завершить этот процесс и создать файл package.json . С этим файлом вы можете хранить записи о модулях, которые вы установили для вашего проекта.

Теперь, когда у вас есть файл package.json , вы можете протестировать установку модулей на следующем шаге.

Шаг 2 — Установка модулей

Обычно в разработке программного обеспечения используются внешние библиотеки для выполнения вспомогательных задач в проектах. Это позволяет разработчику сосредотачивать внимание на бизнес-логике и создавать приложения более быстро и эффективно.

Например, если наш модуль локатора , используемый в качестве примера, должен сделать внешний запрос API для получения географических данных, мы можем использовать библиотеку HTTP, чтобы упростить эту задачу. Поскольку наша основная цель — предоставление пользователю соответствующих географических данных, мы можем установить пакет, упрощающий для нас запросы HTTP вместо повторной записи этого кода, т. к. это задача, выходящая за рамки нашего проекта.

Рассмотрим это на примере. В вашем приложении локатора вы будете использовать библиотеку axios, которая поможет вам выполнять запросы HTTP. Установите ее, введя следующее в оболочке:

Вы начинаете эту команду с npm install​​​ — это установит данный пакет (для краткости можно использовать npm i ). Затем перечисляете пакеты, которые хотите установить, разделяя их пробелом. В этом случае это axios . В заключение вы заканчиваете команду опциональным параметром —save , который указывает, что axios будет сохранен как зависимость проекта.

После установки библиотеки вы увидите примерно следующее:

Теперь откройте файл package.json в текстовом редакторе по вашему выбору. В этом обучающем руководстве мы будем использовать nano :

Вы увидите новое свойство, как подчеркнуто ниже:

Параметр —save указывает npm обновлять package.json с модулем и версиями, которые были только что установлены. Это замечательно, поскольку другие разработчики, работающие над вашим проектами, смогут легко видеть, какие внешние зависимости требуются.

Примечание. Возможно, вы заметили символ ^ перед номером версии для зависимости axios . Вспомните, что семантическое определение версий состоит из трех цифр: MAJOR, MINOR и PATCH. Символ ^ означает, что любая более высокая версия MINOR или PATCH удовлетворит это ограничение версии. Если видите

в начале номера версии, это означает, что только более высокие номера версий PATCH удовлетворяют это ограничение.

После завершения просмотра package.json выйдите из файла.

Зависимости разработки

Пакеты, используемые для разработки проекта, но не для его создания или запуска, называются зависимостями разработки. Они не требуются для вашего модуля или приложения в производственной среде, но могут оказаться полезными при написании кода.

Например, разработчики часто используют инструменты статического анализа кода, чтобы обеспечить соответствие кода передовым практикам и единообразие стиля. Хотя это полезно для разработки, это только увеличивает размер дистрибутива без предоставления ощутимых выгод при развертывании в производственной среде.

Установите инструмент статического анализа кода в качестве зависимости разработки для вашего проекта. Попробуйте это в оболочке:

В этой команде вы использовали флаг —save-dev . Это сохранит eslint как зависимость, которая необходима только для разработки. Обратите внимание, что вы добавили @6.0.0 к своему имени зависимости. После обновления модулей на них ставится тег версии. @ указывает npm искать конкретный тег модуля, который вы устанавливаете. Без указанного тега npm устанавливает последнюю версию с тегами. Откройте package.json еще раз:

В результате вы получите следующий вывод:

eslint сохранился как devDependencies , вместе с номером версии, который вы указали ранее. Выйдите из package.json .

Автоматически сгенерированные файлы: node_modules и package-lock.json

Когда вы в первый раз устанавливаете пакет в проекте Node.js, npm автоматически создает папку node_modules для хранения модулей, необходимых для вашего проекта, и файл package-lock.json , который вы проверили ранее.

Подтвердите, что они находятся в вашей рабочей директории. В вашей оболочке введите ls и нажмите ENTER . Результат будет выглядеть следующим образом:

Папка node_modules содержит все установленные зависимости для вашего проекта. В большинстве случаев вы не должны назначать эту папку вашему репозиторию с контролем версии. По мере того как вы будете устанавливать больше зависимостей, размер этой папки будет быстро расти. Кроме того, файл package-lock.json хранит записи точных версий, установленных более сжато, поэтому включение node_modules не требуется.

Хотя файл package.json перечисляет зависимости, которые указывают нам на соответствующие версии, которые должны быть установлены для проекта, файл package-lock.json отслеживает все изменения в package.json или node_modules и указывает на конкретную версию установленного пакета. Обычно вы управляете этим в вашем репозитории с контролем версий, а не в node_modules , т. к. это более прозрачное представление всех ваших зависимостей.

Установка из package.json

С помощью ваших файлов package.json и package-lock.json вы можете быстро задать те же самые зависимости проекта, прежде чем начать разработку нового проекта. Чтобы продемонстрировать это, перейдите на один уровень выше в дереве директорий и создайте новую папку с именем cloned_locator на том же уровне директории, что и locator :

Перейдите в новую директорию:

Теперь скопируйте файлы package.json и package-lock.json из locator в cloned_locator :

Чтобы установить требуемые модули для этого проекта, введите следующее:

npm проверит файл package-lock.json , чтобы установить модули. Если файл lock недоступен, он будет читать из файла package.json , чтобы определить установки. Обычно быстрее устанавливать из package-lock.json , поскольку файл lock содержит точные версии модулей и их зависимости, что означает, что npm может не тратить время на нахождение подходящей версии для установки.

При развертывании в производственную среду вы можете пропустить зависимости разработки. Вспомните, что зависимости разработки хранятся в разделе devDependencies файла package.json и не влияют на управление вашим приложением. При установке модулей в рамках процесса непрерывной интеграции и разработки, чтобы развернуть приложение, пропустите зависимости разработки, введя следующее:

Флаг —production игнорирует раздел devDependencies во время установки. Пока что перейдите к вашей сборке разработки.

Прежде чем перейти к следующему разделу, вернитесь в папку locator :

Глобальная установка

Пока что вы устанавливали модули npm для проекта locator . npm также позволяет устанавливать пакеты на глобальном уровне. Это означает, что пакет доступен вашему пользователю в более широкой системе, как и любая другая команда оболочки. Эта способность полезна для многих модулей Node.js, которые являются инструментами командной строки.

Например, вы хотите завести блог о проекте locator , над которым вы сейчас работаете. Для этого вы можете использовать библиотеку, например Hexo, для создания и управления вашим блогом на статичном веб-сайте. Установите командную строку Hexo на глобальном уровне следующим образом:

Чтобы установить пакет на глобальном уровне, вы добавляете флаг -g к команде.

Примечание. Если вы получите ошибку разрешений, пытаясь выполнить установку этого пакета на глобальном уровне, ваша система может потребовать права суперпользователя для запуска команды. Попробуйте еще раз команду sudo npm i hexo-cli -g .

Проверьте, что пакет успешно установлен, введя следующее:

Вы увидите примерно следующий результат:

На данный момент вы узнали, как устанавливать модули с помощью npm. Вы можете установить пакеты к проекту локально —либо как зависимость в производственной среде, либо как зависимость разработки. Также вы можете устанавливать пакеты на базе уже существующих файлов package.json или package-lock.json , что позволяет разрабатывать с теми же зависимостями, что и у ваших коллег. В заключение вы можете использовать флаг -g для установки пакетов на глобальном уровне, чтобы получить доступ к ним, независимо от того, находитесь ли вы в проекте Node.js или нет.

Теперь, когда вы можете устанавливать модули, в следующем разделе вы будете практиковать методы управления своими зависимостями.

Шаг 3 — Управление модулями

Полный менеджер пакетов способен на гораздо большее, чем установка модулей. В npm имеется 20 команд, связанных с управлением зависимостями. На этом шаге вы:

  • Укажете модули, которые вы установили.
  • Обновите модули до последней версии.
  • Удалите модули, которые вам больше не нужны.
  • Проведете проверку безопасности на ваших модулях, чтобы найти и исправить ошибки безопасности.

Хотя эти примеры будут сделаны в вашей папке locator , все эти команды могут запускаться на глобальном уровне посредством добавления флага -g в конце, как и в случае установки на глобальном уровне.

Указание модулей

Если вы хотите знать, какие модули установлены в проекте, проще использовать команду list или ls вместо чтения package.json напрямую. Для этого введите следующее:

Результат должен выглядеть следующим образом:

По умолчанию ls отображает все дерево зависимостей — модули, от которых зависит ваш проект, и модули, от которых зависят ваши зависимости. Это может быть довольно неудобно, если вы хотите получить общий обзор того, что установлено.

Чтобы вывести только модули, которые вы установили, без их зависимостей, введите следующее в оболочке:

Результат будет выглядеть следующим образом:

Опция —depth позволяет указать, какой уровень дерева зависимостей вы хотите увидеть. Когда значение 0 , вы увидите только зависимости самого высокого уровня.

Обновление модулей

Это хорошая практика, позволяющая поддерживать ваши модули npm обновленными. Это повышает вашу вероятность получения последних исправлений безопасности для модуля. Используйте команду outdated , чтобы проверить, можно ли обновить какие-либо модули:

Вывод будет выглядеть следующим образом:

Сначала эта команда указывает пакет ( Package ), который установлен, и текущую ( Current​​​ ) версию. В столбце Wanted показано, какая версия удовлетворяет вашему требованию версии в package.json . В столбце Latest показана самая последняя опубликованная версия модуля.

В столбце Location​​​ показано, где в дереве зависимостей находится пакет. Команда outdated имеет флаг —depth , как ls . По умолчанию depth равняется 0.

Похоже, вы можете обновить eslint до последней версии. Используйте команду update или up следующим образом:

Вывод команды будет содержать установленную версию:

Если хотите обновить все модули одновременно, введите следующее:

Удаление модулей

Команда npm uninstall может удалять модули из ваших проектов. Это означает, что модуль больше не будет установлен в папке node_modules и его нельзя будет увидеть в ваших файлах package.json и package-lock.json .

Удаление зависимостей из проекта — обычное мероприятие в жизненном цикле разработки программного обеспечения. Зависимость может не решить проблему, как заявлено, или может не предоставить удовлетворительный опыт разработки. В этих случаях может быть лучше удалить зависимость и создать собственный модуль.

Представьте, что axios не предоставляет опыт разработки, который вы хотели бы иметь для выполнения запросов HTTP. Удалите axios с помощью команды uninstall или un , введя следующее:

Вывод будет выглядеть следующим образом:

Здесь не указано явно, что axios был удален. Чтобы убедиться, что он был удален, еще раз укажите зависимости:

Теперь мы видим только то, что установлен eslint :

Это показывает, что вы успешно удалили пакет axios .

Проверка модулей

npm предоставляет команду audit , чтобы выявить потенциальные риски безопасности в ваших зависимостях. Чтобы увидеть проверку в действии, установите устаревшую версию модуля request​​​, выполнив следующее:

После установки устаревшей версии request ​​ вы должны увидеть примерно следующий результат:

npm указывает, что у вас есть уязвимости в ваших зависимостях. Для получения более подробных сведений проверьте весь ваш проект:

Команда audit показывает таблицы вывода, указывающие на недостатки безопасности:

Вы видите путь к уязвимости, и иногда npm предоставляет способы ее устранения. Вы можете выполнить команду update, как предложено, или выполнить подкоманду fix команды audit . В своей оболочке введите:

Вы увидите примерно следующий результат:

npm смог безопасно обновить два пакета, тем самым устранив две уязвимости. Но у вас все еще есть четыре уязвимости в ваших зависимостях. Команда audit fix не всегда устраняет каждую проблему. Хотя версия модуля может иметь уязвимость безопасности, если вы обновите ее до версии с другим API, то это может нарушить код выше в дереве зависимостей.

Вы можете использовать параметр —force , чтобы обеспечить удаление уязвимости:

Как упоминалось ранее, это не рекомендуется, если вы не уверены, что это не нарушит функциональность.

Заключение

В этом обучающем руководстве вы прошли различные упражнения, чтобы продемонстрировать организацию модулей Node.js в пакетах и управление этими пакетами при помощи npm. В проекте Node.js вы использовали пакеты npm как зависимости, создавая и обслуживая файл package.json — запись метаданных вашего проекта, включая модули, которые вы установили. Вы также использовали инструмент командной строки npm для установки, обновления и удаления модулей, помимо указания дерева зависимостей для ваших проектов, а также проверки и обновления модулей, которые устарели.

В будущем использование существующего кода с помощью модулей ускорит время разработки, так как вам не придется дублировать функциональность. Вы также сможете создавать собственные модули npm, и они, в свою очередь, будут управляться другими модулями с помощью команд npm. В качестве дальнейших шагов экспериментируйте с тем, что вы узнали в этом обучающем руководстве, устанавливая и тестируя различные существующие пакеты. Посмотрите, что предоставляет экосистема для упрощения процесса решения проблем. Например, вы можете попробовать TypeScript — расширенную версию JavaScript, или превратить ваш веб-сайт в мобильные приложения с помощью Cordova. Если хотите узнать больше о Node.js, ознакомьтесь с другими нашими обучающими руководствами по Node.js.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Читать:
Как удалить анимацию в blender

Похожие статьи