Skip to content

Getting started

Installation

Just install it using your favorite package manager.

Needle DI is published to NPM and JSR, and is also compatible with Deno.

bash
npm install @needle-di/core
bash
yarn add @needle-di/core
bash
pnpm install @needle-di/core
bash
deno add jsr:@needle-di/core

Transpiler settings

Needle DI uses ECMAScript stage 3 decorators.

If you're using Deno, you can run your code as-is. However, when using Node.js or a browser as runtime, you will need to transpile your code first, since decorators are not yet supported.

Make sure to use ES2022 or lower as target:

json
{
  "compilerOptions": {
    "target": "ES2022"
  }
}
javascript
export default defineConfig({
  esbuild: {
    target: 'es2022',
    // ...
  },
  // ...
});
bash
esbuild app.js --target=es2022

Basic example

Here’s a simple example using constructor injection to inject one service into another.

typescript
import { injectable, inject } from "@needle-di/core";

@injectable()
class FooService {
    // ...
}

@injectable()
class BarService {
  constructor(private fooService = inject(FooService)) {}
  //                  ^? Type will be inferred as `FooService`
}

As you can see, Needle DI uses default parameter values for constructor injection.

The @injectable decorator eliminates the need to register services manually. To construct the BarService, you have to create a dependency injection container, and use the container.get() method:

typescript
import { Container } from "@needle-di/core";

const container = new Container();
const barService = container.get(BarService);
//    ^? Type will be inferred as `BarService`

That's it!

What's next?

Check out the concepts to learn more and see more examples.

Released under the MIT License