Getting Started
Installation
pnpm add -D alloy-diUsage
1. Configure your bundler
Alloy ships plugins for Vite, webpack, and Rspack. This guide uses Vite; for the others see Webpack / Rspack configuration — the rest of the guide is identical, only the plugin wiring differs.
Add the alloy plugin to your vite.config.ts file.
// vite.config.ts
import { defineConfig } from "vite";
import { alloy } from "alloy-di/vite";
export default defineConfig({
plugins: [alloy()],
});Note: The Alloy plugin generates type definition files (
alloy-container.d.ts,alloy-manifests.d.ts, and — when custom scopes are configured —alloy-scopes.d.ts) in your source directory (default:./src). Add these to your.gitignore.
TIP
The default Vite scaffold (pnpm create vite@latest) wires "build": "tsc && vite build". Run alloy generate before type-checking so fresh checkouts and CI have Alloy's ambient declarations available:
{
"scripts": {
"build": "alloy generate && tsc && vite build"
}
}2. Declare Services
Use decorators from alloy-di/runtime.
Singleton Service:
// service-a.ts
import { Singleton } from "alloy-di/runtime";
@Singleton()
export class ServiceA {
public value = "Hello from singleton ServiceA";
}Transient Service with Dependencies:
// app-service.ts
import { Injectable, deps } from "alloy-di/runtime";
import { ServiceA } from "./service-a";
@Injectable(deps(ServiceA))
export class AppService {
constructor(private serviceA: ServiceA) {}
public getValue() {
return `AppService gets: "${this.serviceA.value}"`;
}
}3. Bootstrap Your Application
Import the container from the virtual module.
// main.ts
import container, { serviceIdentifiers } from "virtual:alloy-container";
async function bootstrap() {
// Resolve via identifier (recommended)
const appService = await container.get(serviceIdentifiers.AppService);
console.log(appService.getValue());
}
bootstrap();