CodeBlanks Logo Icon CodeBlanks

Summary - npm

Combine install, scripts and semver to set up a project.

Summary - npm

In this group you learned the core tools of npm: installing packages with npm install, defining commands with scripts, separating development packages with devDependencies, version ranges with semver and publishing with npm publish.

You can combine these five tools to set up a real project. For example, you can read a package.json and print the name, version and script count. This is the basic way to inspect a package's structure. Now you will combine all pieces in one piece of code.

Practice Print name@version and the script count

Define a string named content with the value {"name":"my-lib","version":"1.0.0","scripts":{"start":"node index.js","test":"jest"}}. Parse it into an object with JSON.parse. First print pkg.name + "@" + pkg.version, then print Object.keys(pkg.scripts).length on a separate line, both with console.log.

Starter code

index.js
// Define the package.json content (name, version, scripts)
// Parse it into an object with JSON.parse
// Print name@version, then the scripts count
// write here

Sample solution

index.js
const content = '{"name":"my-lib","version":"1.0.0","scripts":{"start":"node index.js","test":"jest"}}';
const pkg = JSON.parse(content);
console.log(pkg.name + "@" + pkg.version);
console.log(Object.keys(pkg.scripts).length);

Expected output

my-lib@1.0.0
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each tool to its role

Term Meaning
npm install Installs packages
scripts Defines commands
devDependencies Dev packages
semver Version range

2 What does scripts.test do in package.json?

index.js
scripts.test
  • Deletes test files
  • Installs the test package
  • The script that npm test runs Correct answer
  • Logs during tests

Explanation: The scripts.test field defines the npm test command.

3 Complete the tilde range

Question
"____1.2.3"
Answer
"~1.2.3"

Explanation: ~1.2.3 allows only patch-level updates.

All lessons in Intermediate