0

I am using Webpack. How do I import jQuery into Angular2?

I added to package.json

"jquery": "^3.1.0",

Added this to index.html

    <script src="node_modules/jquery/dist/jquery.min.js"></script>

Will not find

http://localhost:3000/node_modules/jquery/dist/jquery.min.js

I even tried the below:

<script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="../../node_modules/jquery/dist/jquery.min.js"></script>

Yes, jQuery is in node_modules.

halfer
  • 19,824
  • 17
  • 99
  • 186
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • you need for `import $ from "jquery"`, webpack will bundle that for you. Don't use script tags. – Hitmands Sep 13 '16 at 12:02
  • And also this might be interesting for you http://stackoverflow.com/questions/39424340/include-jquery-in-angular2-with-webpack-and-access-it-from-component – yurzui Sep 13 '16 at 12:04
  • this is what i get:L Uncaught (in promise): TypeError: jquery_1.default is not a function – Tampa Sep 13 '16 at 13:49
  • see http://stackoverflow.com/questions/32793404/es6-export-overwriting-function – Tobias Timm Sep 13 '16 at 14:03

2 Answers2

0

You have to either

import * as $ from "jquery"
// or import * as jQuery from "jquery"
// or import * as jquery from "jquery"
// depending on what identifier you want to use for jQuery function

in every file, you use jquery, or edit your webpack.config to recognize jQuery, for example:

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

and of course, remove <script> tags you added from index.html

hendrix
  • 3,364
  • 8
  • 31
  • 46
0

you can also try this:

npm install expose-loader

inside vendor.ts:

import 'expose?jQuery!../node_modules/jquery/dist/jquery.js';

inside your app .ts files. first declare a var named jQuery to get a ref to jQuery.

declare var jQuery: any;
jQuery('#...') ... 
hannes neukermans
  • 12,017
  • 7
  • 37
  • 56