Kris Hollenbeck Kris Hollenbeck - 1 year ago 1305
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.

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

//With systemJs I could do this

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

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.


Answer Source

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';

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

  public test(){

Add the html below to app.component.html

<h1 (click)="test()">

Then run it

ng serve
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download