AI Hints
Home›JavaScript Tutorial›Node and npm
JavaScript · Lesson 107 of 138

npm

Packages and scripts.

⏱ 2 min read▶ Video at 2:08:09🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Other developers have already written code for almost everything. Dates, colours in the terminal, web servers, testing. NPM, the Node package manager, lets you install their packages with one command. It comes with Node.

npm
From the video: npm
  • Code for almost everything
  • Install with one command
  • npm comes with Node

package.json

Every Node project has a package dot JSON. It holds the project's name and version. Type module turns on import and export. Scripts are shortcuts, so NPM start runs node app dot JS. And dependencies lists the packages the project needs, with their versions.

package.jsonjson
{
  "name": "tip-tool",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node app.js",
    "test": "node --test"
  },
  "dependencies": {
    "chalk": "^5.3.0"
  }
}

The commands you need

NPM init creates a package dot JSON. NPM install, with a package name, downloads it into a folder called node modules, and adds it to dependencies. NPM install, on its own, installs everything listed, which is what you do after cloning a project. And NPM run runs a script.

keyvalue
npm init -ynew package.json
npm install chalkadd a package
npm installinstall everything
npm run testrun a script

Good habits

Never commit the node modules folder to git. It can be huge, and anyone can recreate it with NPM install. Keep the package lock file, which records exact versions. Use dev dependencies for tools that only developers need, like testing libraries. And check a package is popular and maintained before you trust it.

keyvalue
node_modules/don't commit it
package-lock.jsondo commit it
--save-devdeveloper tools
Check packagespopular, maintained

Summary

NPM installs packages, package dot JSON describes your project, and scripts give you handy shortcuts. Next, a web server in Node.

Key takeaways
  • package.json
  • npm install
  • npm run
Next up: A Web Server — handling requests