How to Install Matter.js Using npm

Matter.js is a widely used 2D physics engine for web development that simplifies simulating rigid body dynamics. This guide explains how to install Matter.js into your JavaScript or TypeScript project using the npm package manager, complete with prerequisites, the primary installation command, and basic code setup to verify the installation.

Prerequisites

Before installing the package, ensure that Node.js and npm are installed on your machine. You can verify this by checking their versions in your terminal:

node -v
npm -v

If you do not have an existing package.json file in your project directory, initialize one by running:

npm init -y

Installing Matter.js

To install Matter.js and add it to your project's dependencies, run the following command in your terminal:

npm install matter-js

Importing Matter.js in Your Code

Once the package is installed, you can import and use it in your application.

ES Module syntax (modern JavaScript / bundlers):

import Matter from 'matter-js';

// Access Matter modules
const { Engine, Render, Runner, Bodies, Composite } = Matter;

CommonJS syntax (Node.js):

const Matter = require('matter-js');

// Access Matter modules
const { Engine, Render, Runner, Bodies, Composite } = Matter;

Verifying the Installation

To ensure Matter.js is working properly, create a simple script to initialize an engine:

import Matter from 'matter-js';

const engine = Matter.Engine.create();
console.log('Matter.js Engine created successfully:', engine);

Run the file using Node.js or through your project's build tool to confirm that the engine initializes without errors.