问题描述:

How can I setup TweenMax in my Angular2 project. Instead of adding the script in my HTML I want to be able to import TweenMax similar to this:

import { TweenMax } from 'gsap';

NOTE: I'm using angular-cli.

网友答案:

Adding this external package to angular 2 is almost the same like any other package out there. jquery, firebase, you name it..

But you should know that at this moment, there are no typings file for the gsap module. So you can't cherry pick the imports however you want. This also means no intelisense in typescript :( But you can still use it like this:

Step 1: npm install it

npm install gsap --save

Step 2: In the: angular-cli-build.js in the vendor section put this line:

vendorNpmFiles: [
   // angular stuff above

   'gsap/src/**/*.+(js)' // this will add the gsap form node_modules, to the vendor folder, which is dist. Your entire app including when will be in production, loads entirely form the dist folder.
]

Step 3: add mappings and package configuration in system-config.ts ( src folder )

/** Map relative paths to URLs. */
const map: any = {
  'gsap': 'vendor/gsap/src/minified/' // this tells to system.js loader: Hey when you see: "import 'gsap'" in any of my project files, you should load it form: vendor/gsap blah blah..
};

/** User packages configuration. */
const packages: any = {
  gsap: {
    defaultExtension: 'js',
    main: 'TweenMax.min.js' // the entry point for the gsap package.
  }
};

Step 4: prevent typescript for complaining about not finding the clases by adding the following line to typings.d.ts file:

declare var module: { id: string };

declare let TimelineMax: any; // declare it as any.
 // so no error complains, Typescript compiler is happy now:)

Once the typings file are created for this module step 4 becomes:

typings install gsap --save. After that make sure you have included: /// <reference path="../typings/path to your gsap typings" />

Step 5: use it in your component - for example in app.component.ts:

import 'gsap' // this is required for TimelineMax() to work
// decorator stuff here.
export class AppComponent implements OnInit{

  ngOnInit(){

    let targetObject = document.getElementByTagName('h1');

    let tl = TimelineMax(); // this is free of errors now

    tl.from(targetObject, 1, { x:400 });
    tl.play();
  }
}

Step 6: in this setup, there is no need to add anything to the main.ts (bootstrap file) so enjoy!

相关阅读:
Top