Package Manager
We don't want to reinvent the wheel over and over; we want to use packages, libraries, frameworks, etc... to make our lives easier!
Types of package managers
We have several package managers:
- npm
- yarn
- pnpm
- bun
- deno
- ...
npm is the default package manager for node.js; it's the one that's installed by default!
Using npm
Initialize a project
npm init
This will ask you for some information and create a package.json file. You can then use it to install packages.
Install packages
npm install [package_name]
This will install the package in the node_modules folder. You can then use it in your code.
Install development packages
npm install [package_name] --save-dev
This will install the package in the node_modules folder and add it to the package.json file. You can then use it in your code.
Importing packages
To use a library, you can import the package into your code with the following syntax:
Modern syntax (ES6+)
import { package_name } from 'package_name';
Old syntax (CommonJS)
const { package_name } = require('package_name'); // for versions prior to 2015
// (you sometimes find this in old libraries)
Practical example with Three.js
npm init
npm install three
// example code with three.js
import { Three } from 'three';
let scene = new Three.Scene();
let camera = new Three.Camera();
let renderer = new Three.Renderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);