7

I am making a simple angular 2 application using angular cli tool. In my code I have to include jquery.js file in my index.html. jquery.js is under node_modules directory but the statement

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

in the index.html seems to be not working:

Failed to load resource: http://localhost:4200/node_modules/jquery/dist/jquery.js the server responded with a status of 404 (Not Found)

How can I make sure that the jquery.js is included in index.html? Thanks for any help.

2
  • Hi.. are you using webpack also? ..and typescript? Commented Dec 29, 2016 at 9:03
  • @fscamuzzi81 Yes I am using typescript and webpack. Commented Dec 29, 2016 at 9:07

6 Answers 6

6

In order to include a global library, you have to add the jquery.js file in the scripts array from angular-cli.json:

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Tudor. Short, simple and to the point answer!
4

There is a new way to deal with external libraries using @types

In order to install/use jquery, you just need to install it in your project using

npm install --save @types/jquery

and then in tsconfig.json,under types, add its reference accordingly as shown,

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,

    "types": [
      "jquery",    //<<<<-----add here
      "hammerjs",
      "node"
    ]
  }
}

5 Comments

what is the benefit by using this way ? i mean by using @types
earlier there was no mechanism to manage external libraries but now using types only in one file you can manage your external libraries...
which one file ? is there any link related to that mechanism would be more helpful if you provide , btw thanks :)
unfortunately I don't think any official doc is available for the same but take a look here- angular.io/docs/ts/latest/guide/typescript-configuration.html and google it for me. I will get the things easily.
Thank you very much for the solution micronyks. I did not try it right now but I will look at it.
1

If you use webPack and Typescript you can do something like this:

in your vendor.ts file import jquery:

/ RxJS.
import "rxjs";

// Angular 2.
import "@angular/common";
import "@angular/compiler";
import "@angular/core";
import "@angular/http";
import "@angular/platform-browser";
import "@angular/platform-browser-dynamic";
import "@angular/router";

// Reflect Metadata.
import "reflect-metadata";

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

import "jquery"; //<-- HERE IS JQUERY
import "bootstrap/dist/js/bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "angular2-toaster/lib/toaster.css";
import "angular2-toaster/angular2-toaster";

import "ng2-slim-loading-bar";
import "ng2-slim-loading-bar/style.css";
import "ng2-modal";
import "ng2-bs3-modal/ng2-bs3-modal";

then in your webpack.dev.js use plug in to import it in every component without need to import it manually:

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var CleanWebpackPlugin = require('clean-webpack-plugin');
var path = require('path');

module.exports = {
    entry: {
        "polyfills": "./polyfills.ts",
        "vendor": "./vendor.ts",
        "app": "./app/main.ts",

    },
    resolve: {
        extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
    },
    output: {
        path: "./app_build",
        filename: "js/[name]-[hash:8].bundle.js"
    },
    devtool: 'source-map',
    module: {
        loaders: [
            {
                loader: "babel-loader",

                // Skip any files outside of your project's `src` directory
                //include: [
                //  "app_build",
                //],
                exclude: [
                  path.resolve(__dirname, "node_modules")
                ],
                // Only run `.js` and `.jsx` files through Babel
                test: /\.js/,

                // Options to configure babel with
                query: {
                    plugins: ['transform-runtime', 'babel-plugin-transform-async-to-generator'],
                    presets: ['es2015', 'stage-0'],
                }
            },
            {
                test: /\.ts$/,
                loader: "ts"
            },
            {
                test: /\.html$/,
                loader: "html"
            },
            //{
            //    test: /\.(png|jpg|gif|ico|woff|woff2|ttf|svg|eot)$/,
            //    loader: "file?name=assets/[name]-[hash:6].[ext]",
            //},
            {
                test: /\.(png|jpg|gif|ico)$/,
                //include:  path.resolve(__dirname, "assets/img"),
                loader: 'file?name=/assets/img/[name]-[hash:6].[ext]'
            },
            {
                test: /\.(woff|woff2|eot|ttf|svg)$/,
              //  exclude: /node_modules/,
                loader: 'file?name=/assets/fonts/[name].[ext]'
            },
            // Load css files which are required in vendor.ts
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('css!sass')
            },
        ]
    },
    plugins: [
        new ExtractTextPlugin("css/[name]-[hash:8].bundle.css", { allChunks: true }),
        new webpack.optimize.CommonsChunkPlugin({
            name: ["app", "vendor", "polyfills"]
        }),
        new CleanWebpackPlugin(
            [
                "./app_build/js/",
                "./app_build/css/",
                "./app_build/assets/",
                "./app_build/index.html"
            ]
        ),
        // inject in index.html
        new HtmlWebpackPlugin({
            template: "./index.html",
            inject: "body"
        }),
        // JQUERY PLUGIN HERE <-- !!! HERE IS PLUG IN
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery'
        })
    ],
    devServer: {
        //contentBase: path.resolve(__dirname, "app_build/"),
        historyApiFallback: true,
        stats: "minimal"
    }
};

Now everywhere in your code .ts you can use jquery like this:

import { Component, AfterViewInit, ElementRef } from '@angular/core';





@Component({
    selector: 'about',
    template: require('./about.component.html'),
    styles: [String(require('./about.component.scss'))]
})

export default class AboutComponent implements AfterViewInit {
    calendarElement: any;


    constructor(private elementRef: ElementRef) { }

    ngAfterViewInit() {
        this.calendarElement = jQuery(this.elementRef.nativeElement);

    }

}

Comments

1

Firstly you don't need to put it in index.html instead put this entry in angular-cli.json file

Like this:

      "scripts": [
        "../node_modules/wow.js/dist/wow.js",
        "../node_modules/jquery/dist/jquery.js",
        "....Other Libs..."
      ]

Then make sure you have installed jQuery properly before use

Also check the root path while giving relative path in the angular-cli.json file

Comments

0

I recommend to follow Nikhil Shah suggestion in case of existing @type (like the case of jQuery)

However if you have library that export global variable (like jQuery) but does not have known @type file you can take a look at my following answer

Comments

0

If @tudorciotlos answer does not work for you (like in my case) try this extended way:

  "scripts": [
    { "input": "../node_modules/jquery/dist/jquery.js", "bundleName": "renamed-script.js" }
  ]
     <script src="renamed-script.js"></script>

Source here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.