Everything that you need to know about NPM and Packages

Everything that you need to know about NPM and Packages

·

11 min read

So to understand npm, let's first understand why it is needed. Consider that you are building a JavaScript project which uses some packages (think of this as code written by someone else that helps to ease your tasks). Now, you have used that package code in your project, which makes your project dependent on the used packages.

So what npm does is, it helps keep a list of the used packages in a file that assists in tracking/managing them efficiently and maintaining code functionality. npm also makes it easy for developers to share and reuse code.

What is npm?

Node Package Manager (npm), as the name suggests, is a package manager that manages packages for JavaScript runtime node.js. It can also help to install frontend frameworks like Bootstrap.

npm can be divided into three components:

  1. The Website

  2. The Command Line Interface (CLI)

  3. The Registry

The website is where you can explore packages, read their docs, and find information about npm.

Most developers use the CLI tool to interact with npm for installing, updating or deleting packages. It runs from the terminal.

The registry is a database that stores the information and code for the packages, to make packages available for all. The Registry can be private or public.

Installing npm in your local environment

To install npm, node.js needs to be installed on your system, so to check that:

  • open a command line terminal, and run node -v.

    -v is a flag command for "version", or you can also use --version. If node.js is installed, the command should print the node version.

  • If it is not installed in your system then, Node.js must be installed from nodejs.org.

Now, npm comes pre-installed in node.js, so there's no need to install npm separately. But if you want to check, you can run npm -v or npm --version.

what are packages?

A package is a folder or directory containing a program that is described by a package.json file. To publish the package into the npm registry, it must contain a package.json file.

When a package is installed, package-related files are downloaded and stored in the "node_modules" folder that is present in the project directory.

Directory structure with packages installed:

root-directory
    ↳ node_modules
        ↳ package1
        ↳ package2
        ↳ dependent_packages
    ↳ src
    ↳ package.json
    ↳ package-lock.json

About Package.json

The package.json file is a manifest file with all the app information. It is the core of any node.js project. This file stores all the information regarding your project like name, version, and its dependencies and also contains scripts that we can run with the npm run command.

Package.json file helps to clone someone else project in your system with all the dependencies installed and used by them.

Let's create a package.json file

  • Open the terminal in your project directory and run:

      npm init
    
  • Now this will show you a series of questions, which you can answer or press enter to set to default values.

      This utility will walk you through creating a package.json file.
      It only covers the most common items, and tries to guess sensible defaults.
    
      See `npm help init` for definitive documentation on these fields
      and exactly what they do.
    
      Use `npm install <pkg>` afterwards to install a package and
      save it as a dependency in the package.json file.
    
      Press ^C at any time to quit.
      package name: (root_directory)
      version: (1.0.0)
      description: Everything that you need to know about NPM and package.json
      entry point: (index.js)
      test command: 
      git repository:
      keywords:
      author: Mansi Dass
      license: (ISC)
      About to write to C:\Users\Mansi\Desktop\root_directory\package.json:
    
      Is this OK? (yes)
    
  • Now, the package.json file is generated in your root directory which will look something like this:

       {
          "name": "root_directory",
          "version": "1.0.0",
          "description": "Everything that you need to know about NPM and         package.json",
          "main": "index.js",
          "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"
          },
          "author": "Mansi Dass",
          "license": "ISC"
        }|
    

    Context about the fields in the package.json file:

    • name: The name of the project.

    • version: The version of the project (by using semantic versioning).

    • description: A brief description of the project.

    • main: Contains the file name which will be executed when we run the project.

    • scripts: A collection of script commands that can be run with npm run <script-name>.

    • author: The name of the author of the project.

    • license: The license your project is released under.

    • dependencies: The list/collection of packages that the project depends on and use in production.

    • devDependencies: The list/collection of packages that the project depends on and use during development.

  • If you want to generate a package.json with default values at once, which creates a package.json file instantly, run this command:

      npm init -y
      #npm init --yes
    

Changing default values of package.json

  • Set - You can change the default values of various fields in package.json. Just run the command npm set init-<field> "<value>" or npm config set init-<field> "<value>" to change default values for your npm init command, for example:

      npm config set init-author-name "Mansi Dass"
    
  • Get - You can also know the default values for any specific fields by using the command npm get init-<field> or npm config get init-<field> to print out the set default value, for example:

      npm config get init-author-name
      # This will print Mansi Dass, as we changed it earlier.
    
  • Delete - You can also remove any set default value for any specific field by using the command npm config delete init-<field> and it will set to its initial default value, for example:

      npm config delete init-author-name
      #This will delete "Mansi Dass" from default value of author-name.
    

Note - These changes will be made in user and global npmrc files, which means these commands will make changes globally, if you do npm init in any directory, the changes that you made to default values will be applied in the packae.json file.

How to install packages?

Installing a specific package

To install any specific package to your project, run:

npm install <package-name>
#This will install the specified package and 
# save it in dependencies by default in your package.json file.

Some additional flags that can be used with npm install :

  • -P or --save-prod: This will save the installed package in your dependencies, This flag is default unless any other flag is used.

  • -D or --save-dev: This will save your installed package in your devDependencies, the command will look like this: npm install <package-name> -D

  • -O or --save-optional: This will save your package in optionalDependencies. the command will look like this: npm install <package-name> -O

  • --no-save: This will prevent saving installed packages to dependencies.

Installing a specific version of a package

To install a specific version of a package, it's similar to the installation of a specific package, but just need to add a "@" sign with the preferred version number mentioned.

npm install <package-name>@<version-number>

Installing all existing dependencies

If your project already has a package.json file, It has its own set of dependencies(packages that are already used in the project). To install those dependencies in your local working environment, run:

npm install

This command comes in handy while cloning someone's project. It will install all the dependencies with devDependencies in one go.

--production flag can be used with the npm install command to install all the listed packages in dependencies and not install packages listed in devDependencies. The command will look like this: npm install --production .

Let's install a few packages together

  • Open the terminal in your project directory,

  • Make sure your project directory contains a package.json file, if not create one with npm init -y

  • Now we will install a package, chalk which provides terminal string styling, to install we run npm install <package-name> :

      npm install chalk
    
  • Let's install another package, react which is a JavaScript library for creating user interfaces.

      npm install react
    
  • After the packages are installed, you'll see a few changes in the directory:

    • node_modules folder is auto-generated with the packages, you'll see a folder of chalk and react and even other packages, that we don't even install but those are dependencies of our installed packages.

    • The file package-lock.json is auto-generated, it mainly stores the specific version which is installed during production.

  • The file package.json is updated with the installed dependencies:

      {
        "name": "root_directory",
        "version": "1.0.0",
        "description": "Everything that you need to know about NPM and package.json",
        "main": "index.js",
        "scripts": {
          "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "Mansi Dass",
        "license": "ISC",
        "dependencies": {
          "chalk": "^5.2.0",
          "react": "^18.2.0"
        }
      }
    

If you delete the node_modules folder and package-lock.json file, it does not affect your project as it can be regenerated as and when needed.di

But do we need to push these to our GitHub space? it's 50-50, You need to push the package-lock.json file for sure, as this lets the other developer know which versions are used in the development setup, But the node_modules folder doesn't need to be pushed as it can be generated by doing npm install and it is heavy which unnecessarily increase the size of the project.

If you delete the package.json file, Your project will crash as you won't be able to know what dependencies need to be installed, and what scripts are there to test, start or build the project.

  • Now, if you do npm list, It lists all the installed dependencies with their versions, you will see something like this:

      root_directory@1.0.0
      ├── chalk@5.2.0
      └── react@18.2.0
    

How to update a package?

To update a specific package/dependency, you just need to run the npm update command with the specified dependency. The update will be made according to described version number which uses semantic versioning in the package.json file.

npm update <package-name>

How to uninstall a package?

To uninstall a specific package/dependency, you just need to run the npm uninstall command with the specified dependency. This will remove the packages from the node_modules folder and remove the dependency in the package.json and package-lock.json files.

npm uninstall <package-name>
# You can replace uninstall with un, remove, rm, r and unlink.

How to use scripts?

The package.json file supports a format for specifying command-line tasks that can be run by using:

npm run <script-name>

An example of scripts, In which we have few scripts described, one runs the app and the other starts the server. And how their command looks like:

"scripts": {
    "start" : "node app.js", #npm run start - This will run the app 
    "dev" : "live-server" #npm run dev - This will start a live server
  },

Local and Global packages

This can be defined as the scope of the package,

Local Packages - Packages that are installed by running npm install <package-name> in the project directory, this will store the package files in the "node_modules" folder of the project ( that is local to the project ). Local packages are only accessible to that specific project directory.

Global Packages - Packages that are installed by running npm install -g <package-name> in the command line, this will store the package files in a specific place in your system which makes it accessible for every project. You can also know where is that specific location in your system by running the command, npm root -g

Versioning

Npm follows the semantic versioning (semVer) standard, If we look into the dependencies section:

"dependencies": {
    "chalk": "^5.2.0",
    "react": "^18.2.0"
  }
# you can see, packages have some version numbering system

semantic versioning

Break down of version numbering(major.minor.patch), used in semantic versioning.

We'll find <package-name> : <version>, here the mentioned version uses "semantic versioning", which is just a representation of major.minor.patch. Now we have some symbols to tell the installer, which version we want or up to which version we can update. Those symbols are:

  • caret(^): This sign means that the major version should be the same as mentioned but different/latest minor and patch releases are accepted.

  • tilde(~): This sign means that the major and minor versions should be the same as mentioned but a different/latest patch release is accepted.

  • asterisk(*): This sign means the absolute latest version, any major, minor, and patch releases are accepted, with no restrictions and also not recommended to be used.

  • No symbol: If no symbol is present, then the exact version is going to be used.

Example with ^ symbol: If we see React version, "^18.2.0" here the caret(^) sign tells you, to keep 18 as the major version and can bring the latest version for minor and patch (minor and patch can change).

Example with no symbol: If we don't have any symbol mentioned in the version "18.2.0", then the exact version is installed which means major, minor and patch remain the same, no upgraded or latest version is accepted.

You can refer to this, to help you understand semVer: npm semVer calculator


Thank You for reading! don't forget to drop your valuable feedback and suggestions in the comments.

Author: Mansi Dass🤍

Did you find this article valuable?

Support Mansi dass by becoming a sponsor. Any amount is appreciated!