npm.io
1.0.0 • Published 4 months ago

@muxiu1997/vue-easy-di

Licence
MIT
Version
1.0.0
Deps
0
Size
56 kB
Vulns
0
Weekly
0

vue-easy-di

CI npm version LICENSE

Type-safe dependency injection for Vue, simplified into a single composable.

Install

npm install @muxiu1997/vue-easy-di

Usage

Basic
import defineUseDependencyInjection from '@muxiu1997/vue-easy-di'

// Define a DI composable
const useFoo = defineUseDependencyInjection<Foo>()

// Provide in parent component
useFoo('provide', () => new Foo())

// Inject in child component
const foo = useFoo() // foo: Foo | undefined
const foo = useFoo('inject') // equivalent
With Default Initializer
// The initializer is called automatically in provide mode
const useFoo = defineUseDependencyInjection(() => new Foo())

useFoo('provide') // uses default initializer
useFoo('provide', () => new Bar()) // overrides initializer
const foo = useFoo() // foo: Foo | undefined
With Inject Default
// Fallback value when no provider is found
const useFoo = defineUseDependencyInjection<Foo>({
  injectDefault: () => Foo.empty(),
})

const foo = useFoo() // foo: Foo (never undefined)
With Throw On No Provider
// Throws when no provider is found
const useFoo = defineUseDependencyInjection<Foo>({
  throwOnNoProvider: () => new Error('Foo provider is required'),
})

const foo = useFoo() // foo: Foo (throws if no provider)
Override Options at Inject Site
const useFoo = defineUseDependencyInjection<Foo>()

// Override injectDefault
const foo = useFoo('inject', { injectDefault: () => Foo.empty() })

// Override throwOnNoProvider
const foo = useFoo('inject', { throwOnNoProvider: () => new Error('missing') })

Development

Prerequisites
Setup
git clone https://github.com/MuXiu1997/vue-easy-di.git
cd vue-easy-di
pnpm install
Scripts
  • pnpm run lint — Lint and auto-fix.
  • pnpm run test — Run tests with type checking.
  • pnpm run coverage — Run tests with coverage report.
  • pnpm run build — Build the library.

License

This project is licensed under the MIT License.