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.
npm install @needle-di/core
yarn add @needle-di/core
pnpm install @needle-di/core
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:
{
"compilerOptions": {
"target": "ES2022"
}
}
export default defineConfig({
esbuild: {
target: 'es2022',
// ...
},
// ...
});
esbuild app.js --target=es2022
Basic example
Here’s a simple example using constructor injection to inject one service into another.
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:
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.