How to Install and Import Pixi.js Using npm
This article provides a straightforward, step-by-step guide on how to integrate Pixi.js into a modern web application using npm. You will learn how to install the Pixi.js package, import it into your JavaScript or TypeScript files using ES modules, and initialize a basic application to verify the setup is working correctly.
Step 1: Install Pixi.js via npm
To get started, navigate to your project’s root directory in your terminal and run the following command to install the latest version of Pixi.js:
npm install pixi.jsStep 2: Import Pixi.js in Your JavaScript/TypeScript File
In modern web development, bundlers like Vite, Webpack, or Parcel
allow you to use ES import syntax. Open your main script file (e.g.,
main.js or index.ts) and import the necessary
modules from the pixi.js package:
import { Application, Sprite, Assets } from 'pixi.js';Step 3: Initialize the Pixi.js Application
With the modern release of Pixi.js (v8), the initialization process is asynchronous. Below is a clean, minimal setup to initialize the application and append its canvas to the HTML document.
// 1. Create a new PixiJS Application instance
const app = new Application();
async function setup() {
// 2. Initialize the application with your configuration
await app.init({
width: 800,
height: 600,
backgroundColor: 0x1099bb
});
// 3. Append the canvas element to the DOM
document.body.appendChild(app.canvas);
}
// Run the setup function
setup().catch(console.error);Step 4: Add a Simple Graphic (Optional Verification)
To ensure everything is rendering correctly, you can add a simple graphic inside your initialization function:
import { Application, Graphics } from 'pixi.js';
const app = new Application();
async function setup() {
await app.init({ width: 800, height: 600, backgroundColor: 0x1099bb });
document.body.appendChild(app.canvas);
// Create a simple red rectangle
const rectangle = new Graphics()
.rect(0, 0, 150, 150)
.fill({ color: 0xff0000 });
// Position the rectangle
rectangle.x = 100;
rectangle.y = 100;
// Add it to the stage
app.stage.addChild(rectangle);
}
setup().catch(console.error);Your bundler will now compile the Pixi.js library along with your custom code, allowing you to build high-performance 2D graphics inside your web application.