Velidan
Velidan

Reputation: 6004

How to import jquery to vendor.ts Angular 2 webpack

I am trying to set up angular 2 app based on webpack. I see that in vendor.ts we have that structure.

// Angular 2
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';

// RxJS
import 'rxjs';


// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...

I want to import jQuery (for example) but I don't know what. Because when I tried to do that but it's not working. What I'm doing wrong? Thanks for any help.

import 'jquery/dist/jquery.min.js';

So I don't have idea why rxjs imported OK but jquery not :)

Upvotes: 2

Views: 2727

Answers (1)

Alex Paramonov
Alex Paramonov

Reputation: 2730

This is how I implemented it:

  1. I have an alias in resolve section of my Webpack config file:

    resolve: { ... alias: { jquery: "jquery/src/jquery" } }

    this will allow you to write

    import 'jquery';

    instead of

    import 'jquery/dist/jquery.min.js';

    in vendor.ts

  2. Use Webpack ProvidePlugin to make jQuery and $ global:

    plugins: [ ... new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', "window.jQuery": 'jquery' }), ... ]

I may be wrong (just starting with ng2 myself) but I think that by importing angular/core in vendor.ts you tell Webpack to include that module into the resulting bundle, and later in your code you usually import some specific parts of the module like import { NgModule } from '@angular/core'; - that way you can use NgModule in your code.

Upvotes: 2

Related Questions