Kris Hollenbeck Kris Hollenbeck - 3 months ago 653
Javascript Question

Angular Cli Webpack, How to add or bundle external js files?

I am not sure how to include JS files (vendors) after switching Angular Cli from SystemJs to Webpack.

For example

Option A

I have some js files that were installed via npm. Adding script tags to the head tag like this does not work. Nor does it seem like the best way.

<head>
<script src="node_modules/some_package/somejs.js">
</head>

//With systemJs I could do this

<head>
<script src="vendor/some_package/somejs.js">
</head>


Option B

Include these js files as part of the webpack bundle. This seems like the way it probably should be done. However I am not sure how to do this as all of the webpack conig seems to be hidden behind the angular-cli-webpack package. I was thinking maybe there is another webpack config that we might have access to. But I am not sure as I didn't see one when creating a new angular-cli-webpack project.

More Info:

The js files I am trying to include need to be included before the Angular project. For example jQuery and a third party js lib that isn't really setup for module loading or typescript.

References
https://github.com/angular/angular-cli/blob/master/WEBPACK_UPDATE.md
https://github.com/angular/angular-cli/tree/webpack

Answer

With Typescript 2.0 there seems be some configuration by convention where it will automatically bundle jQuery with the Angular2 build without explicitly telling it to if you npm install @types/jquery and jquery and it's reference in an import.

ng new testapp
cd testapp
npm install --save-dev angular-cli@webpack
npm install --save @types/jquery
npm install --save jquery

Then add code below to app.component.ts

import { Component } from '@angular/core';
import * as jQuery from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  title = 'app works!';

  public test(){
    jQuery('h1').text('Magic');
  }
}

Add the html below to app.component.html

<h1 (click)="test()">
  {{title}}
</h1>

Then run it

ng serve