package.json
- Node.js course
- Beginner
- Lesson 4/116
- 4 min
Learn the package.json structure and npm.
What is package.json?
package.json is the heart of a Node.js project. It holds the project's name, version, dependencies and commands.
You can write the file by hand or generate it with npm init -y. npm (Node Package Manager) is used to install and manage Node.js packages.
Thanks to this file, you can recreate the project on another machine with the same dependencies; npm install is enough.
The scripts field
The scripts field inside package.json lets you save frequently used commands under short names. For example, the definition below has two commands, start and test:
"scripts": {
"start": "node app.js",
"test": "node test.js"
}With this definition, typing npm start is the same as running node app.js. npm run test runs the test command. This way you manage commands in one place and share them with teammates.
Practice Define a config object
Define an object named config. The name field is calc, version is 1.0.0, and scripts.start is node index.js. Then call console.log with config.name and config.version.
Starter code
const config = {
// Add name, version and scripts fields
};
// Log config.name and config.versionSample solution
const config = {
name: "calc",
version: "1.0.0",
scripts: {
start: "node index.js"
}
};
console.log(config.name);
console.log(config.version);Expected output
calc 1.0.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is package.json used for?
- Only as a text store
- To write JavaScript code
- To hold project info and dependencies Correct answer
- To store image files
Explanation: package.json holds project info and dependencies.
2 Run the build script
If package.json has "build": "node build.js", to run it you type ____.
If package.json has "build": "node build.js", to run it you type npm run build.
Explanation: Custom scripts are run with npm run.
3 Match the package concepts
| Term | Meaning |
|---|---|
npm |
Package manager |
package.json |
Project info |
node_modules |
Dependency folder |
npm install |
Install dependencies |