Typescript autoinject in Aurelia
How does @autoInject() work?
Before you need to aware of TypeScript's
emitDecoratorMetadata
flag causes the TypeScript compiler to polyfill the Metadata Reflection API and add a special decorator definition to the transpiled TypeScript code.Aurelia's @autoInject() decorator consumes the type metadata created by TypeScript's decorator and applies it to the class in the same way that the @inject(...) decorator does.
Try like below and you need to enable the new option in the compilerOptions
of Type Script.
TS Configuration:
{ "version": "1.5.1", "compilerOptions": { "target": "es5", "module": "amd", "declaration": false, "noImplicitAny": false, "removeComments": false, "noLib": true, "emitDecoratorMetadata": true }, "filesGlob": [ "./**/*.ts", "!./node_modules/**/*.ts" ], "files": [ // ... ]}
Snippet Screenshot from Article:
Article about emitDecoratorMetadata:
http://blog.durandal.io/2015/05/06/getting-started-with-aurelia-and-typescript/http://www.danyow.net/inversion-of-control-with-aurelia-part-2/
Available Type Script Options:
https://github.com/Microsoft/TypeScript/wiki/Compiler-Options
You can do it with Gulp-Typescript as well with Gulp option
Options: https://github.com/ivogabe/gulp-typescript#options
GitHub Issue Thread: https://github.com/ivogabe/gulp-typescript/issues/100
Gulp Code Snippet: gulp.task('build-ts', [], function() {
return gulp.src(paths.typescript) .pipe(plumber()) .pipe(changed(paths.output, {extension: '.js'})) .pipe(sourcemaps.init()) .pipe(ts({ declarationFiles: false, noExternalResolve: true, target: 'es5', module: 'commonjs', emitDecoratorMetadata: true, typescript: typescript })) .pipe(sourcemaps.write()) .pipe(gulp.dest(paths.output));});
What exactly @autoinject & @inject contains ?
As per dependency-injection
Library of the aurelia
Framework.
/** * Decorator: Directs the TypeScript transpiler to write-out type metadata for the decorated class. */ export function autoinject(potentialTarget?: any): any { let deco = function(target) { target.inject = metadata.getOwn(metadata.paramTypes, target) || _emptyParameters; }; return potentialTarget ? deco(potentialTarget) : deco; } /** * Decorator: Specifies the dependencies that should be injected by the DI Container into the decoratored class/function. */ export function inject(...rest: any[]): any { return function(target, key, descriptor) { // if it's true then we injecting rest into function and not Class constructor if (descriptor) { const fn = descriptor.value; fn.inject = rest; } else { target.inject = rest; } }; }
Source URL: https://github.com/aurelia/dependency-injection/blob/master/src/injection.js