Attempting to integrate aws-sdk with an Angular 2 project (generated using angular cli) proved challenging for me as I couldn't load the libraries correctly in the browser.
Following the guidelines from the Angular documentation, I attempted to import the AWS libraries (https://github.com/angular/angular-cli/wiki/3rd-party-libs#adding-underscore-library-to-your-project).
Here's what it looked like:
1. Update package.json to fetch JS file from NPM and save it locally
{
...
"dependencies": {
"aws-sdk": "git://github.com/aws/aws-sdk-js.git#support/typescript"
},
...
}
2. Modify angluar-cli-build.js to include copying AWS JS files to the vendor folder during the build process
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
...
'aws-sdk/**/*.js'
]
});
};
3. Edit the mapping section in system-config.ts to link the namespace to the destination file
const map: any = {
'aws-sdk': 'vendor/aws-sdk/dist/aws-sdk.js'
};
When trying to import the AWS libs in my TypeScript file, I encountered issues.
...
import * as AWS from 'aws-sdk';
...
@Injectable()
export class MyService {
public myMethod() {
var s3 = new AWS.S3();
...
...
...
The TypeScript compiler seemed fine, the source file loaded in the browser, but I kept getting an error stating that "S3 is not a constructor."
Upon debugging, I discovered that after executing "import * as AWS from 'aws-sdk'", the variable AWS was populated with an unexpected object.
My workaround:
1. Update package.json to fetch the JS file from NPM and store it locally
{
...
"dependencies": {
"aws-sdk": "git://github.com/aws/aws-sdk-js.git#support/typescript"
},
...
}
2. Adjust angluar-cli-build.js to copy AWS JS files to the vendor folder of dist during the build process
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
...
'aws-sdk/**/*.js'
]
});
};
3. Add script import to index.html
<script src="/vendor/aws-sdk/dist/aws-sdk.js" type="text/javascript"></script>
4. Utilize it in your service
// declare AWS as 'any' to assist the TypeScript compiler
declare var AWS:any;
@Injectable()
export class MyService {
public myMethod() {
var s3= new AWS.S3();
...
...
...
This approach combines Angular 2's build process and NPM package management while avoiding the use of AWS TypeScript type definitions.