├── .circleci └── config.yml ├── .editorconfig ├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .npmignore ├── .postcssrc.js ├── .prettierignore ├── .prettierrc ├── LICENSE ├── README.md ├── babel.config.js ├── jest.config.js ├── package.json ├── public ├── favicon.ico └── index.html ├── samples ├── App.vue ├── main.ts ├── modules │ └── MyModule.ts ├── router.ts ├── services │ ├── AnotherService.ts │ └── TestService.ts ├── shims-vue.d.ts └── views │ ├── About.ts │ ├── About.vue │ ├── Home.ts │ └── Home.vue ├── src ├── decorators.ts ├── index.ts ├── install.ts └── utils.ts ├── tests └── unit │ └── component.spec.ts ├── tsconfig.json ├── tsconfig.prod.json └── tslint.json /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Javascript Node CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-javascript/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | - image: circleci/node:8.9.4 10 | steps: 11 | - checkout 12 | 13 | # Download and cache dependencies 14 | - restore_cache: 15 | keys: 16 | - v1-dependencies-{{ checksum "package.json" }} 17 | # fallback to using the latest cache if no exact match is found 18 | - v1-dependencies- 19 | 20 | - run: yarn install 21 | 22 | - save_cache: 23 | paths: 24 | - node_modules 25 | key: v1-dependencies-{{ checksum "package.json" }} 26 | 27 | # run tests! 28 | - run: yarn test:unit 29 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | end_of_line = lf 10 | # editorconfig-tools is unable to ignore longs strings or urls 11 | max_line_length = null 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | - **I'm submitting a ...** 2 | [ ] bug report 3 | [ ] feature request 4 | [ ] question about the decisions made in the repository 5 | [ ] question about how to use this project 6 | 7 | - **Summary** 8 | 9 | * **Other information** (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us to have context, eg. StackOverflow, personal fork, etc.) 10 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | - **What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...) 2 | 3 | * **What is the current behavior?** (You can also link to an open issue here) 4 | 5 | - **What is the new behavior (if this is a feature change)?** 6 | 7 | * **Other information**: 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | /build 3 | 4 | # local env files 5 | .env.local 6 | .env.*.local 7 | 8 | # Log files 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | 13 | # Editor directories and files 14 | .idea 15 | .vscode 16 | *.suo 17 | *.ntvs* 18 | *.njsproj 19 | *.sln 20 | *.sw* 21 | 22 | yarn.lock 23 | package-lock.json 24 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .github 3 | /node_modules 4 | /public 5 | /samples 6 | /build/tests 7 | /build/samples 8 | /src 9 | /tests 10 | 11 | .prettierignore 12 | .prettierrc 13 | .editorconfig 14 | .postcssrc.js 15 | babel.config.js 16 | jest.config.js 17 | tsconfig.json 18 | tsconfig.prod.json 19 | tslint.json 20 | .circleci 21 | 22 | # Log files 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | yarn.lock 28 | package-lock.json 29 | -------------------------------------------------------------------------------- /.postcssrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | autoprefixer: {} 4 | } 5 | } -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # package.json is formatted by package managers, so we ignore it here 2 | package.json 3 | **/*.md 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "printWidth": 100 4 | } 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Sascha Braun 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vue-typedi 2 | 3 | Use [typedi](http://github.com/pleerock/typedi) injections in Vue components 4 | 5 | ## Usage 6 | 7 | 1. Install module: 8 | 9 | `npm install vue-typedi --save` 10 | 11 | 2. Install reflect-metadata package: 12 | 13 | `npm install reflect-metadata --save` 14 | 15 | and import it somewhere in the global place of your app before any service declaration or import (for example in app.ts): 16 | 17 | `import "reflect-metadata";` 18 | 19 | 3. Enabled following settings in tsconfig.json: 20 | 21 | ```json 22 | "emitDecoratorMetadata": true, 23 | "experimentalDecorators": true, 24 | ``` 25 | 26 | 4. Use the module: 27 | ```ts 28 | import Vue from 'vue' 29 | import VueTypedi from 'vue-typedi' 30 | 31 | Vue.use(VueTypedi); 32 | ``` 33 | 34 | ## Example 35 | 36 | ```ts 37 | 38 | import { Inject } from 'vue-typedi'; 39 | import MyService from '...'; 40 | 41 | @Component 42 | export default class MyComponent extends Vue { 43 | 44 | @Inject() 45 | public myService!: MyService; 46 | } 47 | 48 | ``` 49 | 50 | ## Decorators 51 | 52 | - `@Inject()` to inject a service in your Vue components or other services. 53 | 54 | - `@Injectable()` allows us to inject the services in non service classes. 55 | 56 | ## License 57 | 58 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details 59 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/app' 4 | ] 5 | } -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | moduleFileExtensions: ["js", "jsx", "json", "vue", "ts", "tsx"], 3 | transform: { 4 | "^.+\\.vue$": "vue-jest", 5 | ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": 6 | "jest-transform-stub", 7 | "^.+\\.tsx?$": "ts-jest" 8 | }, 9 | moduleNameMapper: { 10 | "^@/(.*)$": "/src/$1" 11 | }, 12 | snapshotSerializers: ["jest-serializer-vue"], 13 | testMatch: [ 14 | "**/tests/unit/**/*.spec.(ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)" 15 | ], 16 | testURL: "http://localhost/" 17 | }; 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-typedi", 3 | "version": "1.1.1", 4 | "description": "Use typedi injections in Vue components", 5 | "main": "build/src/index.js", 6 | "typings": "build/src/index.d.ts", 7 | "repository": "https://github.com/sascha245/vue-typedi", 8 | "license": "MIT", 9 | "keywords": [ 10 | "vue", 11 | "typedi" 12 | ], 13 | "scripts": { 14 | "serve": "vue-cli-service serve ./samples/main.ts", 15 | "build": "rimraf ./build && tsc -p tsconfig.prod.json", 16 | "lint": "vue-cli-service lint", 17 | "test:unit": "vue-cli-service test:unit --verbose", 18 | "validate": "npm run build && npm run test:unit && npm pack --dry-run" 19 | }, 20 | "dependencies": { 21 | "reflect-metadata": "^0.1.12", 22 | "typedi": "^0.8.0" 23 | }, 24 | "devDependencies": { 25 | "@types/jest": "^23.1.4", 26 | "@vue/cli-plugin-babel": "^3.0.4", 27 | "@vue/cli-plugin-typescript": "^3.0.4", 28 | "@vue/cli-plugin-unit-jest": "^3.0.4", 29 | "@vue/cli-service": "^3.0.4", 30 | "@vue/test-utils": "^1.0.0-beta.20", 31 | "babel-core": "7.0.0-bridge.0", 32 | "lint-staged": "^7.2.2", 33 | "rimraf": "^2.6.2", 34 | "ts-jest": "^23.0.0", 35 | "tslint-config-prettier": "^1.15.0", 36 | "typescript": "^3.0.0", 37 | "vue": "^2.5.17", 38 | "vue-class-component": "^6.3.2", 39 | "vue-property-decorator": "^7.0.0", 40 | "vue-router": "^3.0.1", 41 | "vue-template-compiler": "^2.5.17" 42 | }, 43 | "gitHooks": { 44 | "pre-commit": "lint-staged" 45 | }, 46 | "lint-staged": { 47 | "*.ts": [ 48 | "vue-cli-service lint", 49 | "git add" 50 | ], 51 | "*.vue": [ 52 | "vue-cli-service lint", 53 | "git add" 54 | ] 55 | }, 56 | "peerDependencies": { 57 | "vue": "^2.5.17", 58 | "vue-class-component": "^6.3.2" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sascha245/vue-typedi/f6232b1c5735e3edf94c04256d54e34ad5d07f22/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | vuex-simple 10 | 11 | 12 | 13 | 16 |
17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /samples/App.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 32 | -------------------------------------------------------------------------------- /samples/main.ts: -------------------------------------------------------------------------------- 1 | import 'reflect-metadata'; 2 | 3 | import Vue from 'vue'; 4 | 5 | import VueTypedi, { Container } from '../src'; 6 | import App from './App.vue'; 7 | import router from './router'; 8 | 9 | Vue.config.productionTip = false; 10 | 11 | Vue.use(VueTypedi); 12 | 13 | Container.set('token', 'myToken'); 14 | 15 | new Vue({ 16 | render: h => h(App), 17 | router 18 | }).$mount('#app'); 19 | -------------------------------------------------------------------------------- /samples/modules/MyModule.ts: -------------------------------------------------------------------------------- 1 | import { Container, Inject, Injectable } from '../../src'; 2 | import { AnotherService } from '../services/AnotherService'; 3 | 4 | @Injectable() 5 | export class MyModule { 6 | @Inject() 7 | public anotherService!: AnotherService; 8 | } 9 | 10 | Container.set('myModule', new MyModule()); 11 | -------------------------------------------------------------------------------- /samples/router.ts: -------------------------------------------------------------------------------- 1 | import Vue from "vue"; 2 | import Router from "vue-router"; 3 | 4 | import About from "./views/About"; 5 | import Home from "./views/Home"; 6 | 7 | Vue.use(Router); 8 | 9 | export default new Router({ 10 | routes: [ 11 | { 12 | component: Home, 13 | name: "home", 14 | path: "/", 15 | }, 16 | { 17 | component: About, 18 | name: "about", 19 | path: "/about", 20 | } 21 | ] 22 | }); 23 | -------------------------------------------------------------------------------- /samples/services/AnotherService.ts: -------------------------------------------------------------------------------- 1 | import { Service } from '../../src'; 2 | 3 | @Service() 4 | export class AnotherService {} 5 | -------------------------------------------------------------------------------- /samples/services/TestService.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Service } from '../../src'; 2 | import { AnotherService } from './AnotherService'; 3 | 4 | @Service() 5 | export class TestService { 6 | @Inject() 7 | public anotherService!: AnotherService; 8 | 9 | public random(min, max) { 10 | const diff = max - min; 11 | return Math.random() * diff + min; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /samples/shims-vue.d.ts: -------------------------------------------------------------------------------- 1 | declare module '*.vue' { 2 | import Vue from 'vue'; 3 | export default Vue; 4 | } 5 | -------------------------------------------------------------------------------- /samples/views/About.ts: -------------------------------------------------------------------------------- 1 | import { Component, Vue } from "vue-property-decorator"; 2 | 3 | @Component({ 4 | components: {} 5 | }) 6 | export default class About extends Vue {} 7 | -------------------------------------------------------------------------------- /samples/views/About.vue: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /samples/views/Home.ts: -------------------------------------------------------------------------------- 1 | import { Component, Vue } from 'vue-property-decorator'; 2 | 3 | import { Inject } from '../../src'; 4 | import { MyModule } from '../modules/MyModule'; 5 | import { TestService } from '../services/TestService'; 6 | 7 | @Component 8 | export default class Home extends Vue { 9 | @Inject() 10 | public testService!: TestService; 11 | 12 | @Inject('token') 13 | public token!: string; 14 | 15 | @Inject('myModule') 16 | public myModule!: MyModule; 17 | 18 | public randomNumber: number = 0; 19 | 20 | public async random() { 21 | this.randomNumber = this.testService.random(-1000, 1000); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /samples/views/Home.vue: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | 14 | 16 | -------------------------------------------------------------------------------- /src/decorators.ts: -------------------------------------------------------------------------------- 1 | import { Container, Inject as TypediInject, Token } from 'typedi'; 2 | import Vue from 'vue'; 3 | import { createDecorator } from 'vue-class-component'; 4 | 5 | import { setInjection } from './utils'; 6 | 7 | type InjectType = ((type?: any) => Function) | string | Token; 8 | 9 | export function Inject(type?: (type?: any) => Function): Function; 10 | export function Inject(serviceName?: string): Function; 11 | export function Inject(token: Token): Function; 12 | 13 | export function Inject(typeOrName?: InjectType) { 14 | return (target: any, propertyName: string, index?: number) => { 15 | if (target instanceof Vue) { 16 | // Use special injection method 17 | let identifier: any; 18 | if (typeof typeOrName === 'string') { 19 | identifier = typeOrName; 20 | } else if (typeOrName instanceof Token) { 21 | identifier = typeOrName; 22 | } else { 23 | identifier = (Reflect as any).getMetadata('design:type', target, propertyName); 24 | } 25 | 26 | const value = () => Container.get(identifier); 27 | const decorator = createDecorator(options => { 28 | setInjection(options, propertyName, value); 29 | }); 30 | decorator(target, propertyName, index!); 31 | } else { 32 | // Use typedi inject 33 | const decorator = TypediInject(typeOrName as any); 34 | decorator(target, propertyName, index); 35 | } 36 | }; 37 | } 38 | 39 | export function Injectable() { 40 | return (target: T) => { 41 | const handlers = Container.handlers.filter(handler => handler.object.constructor === target); 42 | 43 | const type = function(...args: any[]) { 44 | const instance = new target(...args); 45 | handlers.forEach(handler => { 46 | if (handler.propertyName) { 47 | instance[handler.propertyName] = handler.value(Container.of(undefined)); 48 | } 49 | }); 50 | return instance; 51 | } as any; 52 | 53 | type.prototype = target.prototype; 54 | return type; 55 | }; 56 | } 57 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { install } from './install'; 2 | 3 | export { 4 | Container, 5 | ContainerInstance, 6 | Handler, 7 | ObjectType, 8 | Service, 9 | ServiceIdentifier, 10 | ServiceMetadata, 11 | ServiceOptions, 12 | Token 13 | } from 'typedi'; 14 | 15 | export * from './decorators'; 16 | 17 | export default { 18 | install 19 | }; 20 | -------------------------------------------------------------------------------- /src/install.ts: -------------------------------------------------------------------------------- 1 | import { getInjections } from './utils'; 2 | 3 | export function install(vue: any) { 4 | vue.mixin({ 5 | beforeCreate() { 6 | const injections = getInjections(this.$options); 7 | if (injections) { 8 | injections.forEach((value, propertyName) => { 9 | this[propertyName] = value(); 10 | }); 11 | } 12 | } 13 | }); 14 | } 15 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | interface OptionInjections { 2 | __injections__: Map any>; 3 | } 4 | 5 | export function setInjection(options: any, propertyName: string, value: () => any) { 6 | const opt = options as OptionInjections; 7 | if (!opt.__injections__) { 8 | opt.__injections__ = new Map(); 9 | } 10 | opt.__injections__.set(propertyName, value); 11 | } 12 | export function getInjections(options: any) { 13 | const opt = options as OptionInjections; 14 | return opt.__injections__; 15 | } 16 | export function getInjection(options: any, propertyName: string): (() => T) | undefined { 17 | const opt = options as OptionInjections; 18 | if (!opt.__injections__) { 19 | return undefined; 20 | } 21 | return opt.__injections__.get(propertyName); 22 | } 23 | -------------------------------------------------------------------------------- /tests/unit/component.spec.ts: -------------------------------------------------------------------------------- 1 | import 'reflect-metadata'; 2 | 3 | import Vue from 'vue'; 4 | 5 | import { mount } from '@vue/test-utils'; 6 | 7 | import Home from '../../samples/views/Home'; 8 | import VueTypedi, { Container } from '../../src'; 9 | 10 | Vue.use(VueTypedi); 11 | 12 | Container.set('token', 'myToken'); 13 | 14 | describe('Vue Component', () => { 15 | it('testModule is injected', () => { 16 | const wrapper = mount(Home, {}); 17 | 18 | const vm: Home = wrapper.vm; 19 | 20 | expect(vm.testService).not.toBeUndefined(); 21 | }); 22 | 23 | it('anotherModule is injected', () => { 24 | const wrapper = mount(Home, {}); 25 | 26 | const vm: Home = wrapper.vm; 27 | 28 | expect(vm.testService).not.toBeUndefined(); 29 | expect(vm.testService.anotherService).not.toBeUndefined(); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "module": "esnext", 5 | "strict": true, 6 | "jsx": "preserve", 7 | "noImplicitThis": false, 8 | "noImplicitAny": false, 9 | "declaration": true, 10 | "importHelpers": true, 11 | "moduleResolution": "node", 12 | "experimentalDecorators": true, 13 | "emitDecoratorMetadata": true, 14 | "esModuleInterop": true, 15 | "allowSyntheticDefaultImports": true, 16 | "sourceMap": true, 17 | "baseUrl": ".", 18 | "types": ["webpack-env", "jest"], 19 | "lib": ["esnext", "dom", "dom.iterable", "scripthost"] 20 | }, 21 | "include": [ 22 | "src/**/*.ts", 23 | "samples/**/*.ts", 24 | "samples/**/*.tsx", 25 | "samples/**/*.vue", 26 | "tests/**/*.ts", 27 | "tests/**/*.tsx" 28 | ], 29 | "exclude": ["node_modules"] 30 | } 31 | -------------------------------------------------------------------------------- /tsconfig.prod.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "strict": true, 6 | "jsx": "preserve", 7 | "outDir": "build", 8 | "noImplicitThis": false, 9 | "noImplicitAny": false, 10 | "declaration": true, 11 | "importHelpers": true, 12 | "moduleResolution": "node", 13 | "experimentalDecorators": true, 14 | "emitDecoratorMetadata": true, 15 | "esModuleInterop": true, 16 | "allowSyntheticDefaultImports": true, 17 | "sourceMap": true, 18 | "baseUrl": ".", 19 | "lib": ["es2015", "dom", "dom.iterable", "scripthost"] 20 | }, 21 | "include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"], 22 | "exclude": ["node_modules"] 23 | } 24 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint:latest", "tslint-config-prettier"], 3 | "defaultSeverity": "warn", 4 | "linterOptions": { 5 | "exclude": ["node_modules/**"] 6 | }, 7 | "rules": { 8 | "interface-name": [true, "never-prefix"], 9 | "variable-name": false, 10 | // TODO: allow devDependencies only in **/*.spec.ts files: 11 | // waiting on https://github.com/palantir/tslint/pull/3708 12 | // "no-implicit-dependencies": [true, "dev"], 13 | "ban-types": false, 14 | "member-ordering": false, 15 | "curly": false, 16 | "no-empty": false, 17 | "no-implicit-dependencies": false, // else linter throws an error when using vue-router in samples 18 | "prefer-conditional-expression": false, 19 | "unified-signatures": false, // it is cleaner to separate multiple signatures 20 | "only-arrow-functions": false // needed for wrapper constructor 21 | } 22 | } 23 | --------------------------------------------------------------------------------