angular2引用index.html中的外部js文件

时间:2016-12-29 09:00:05

标签: angular

我正在使用角度cli工具制作一个简单的角度2应用程序。在我的代码中,我必须在index.html中包含jquery.js文件。 jquery.js位于node_modules目录下,但语句为

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

index.html中的

似乎无效:

无法加载资源:http://localhost:4200/node_modules/jquery/dist/jquery.js 服务器响应状态为404(未找到)

如何确保jquery.js包含在index.html中?谢谢你的帮助。

6 个答案:

答案 0 :(得分:5)

为了包含一个全局库,你必须在angular-cli.json的scripts数组中添加jquery.js文件:

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

在此之后,如果已经启动,请重新启动ng serve

答案 1 :(得分:4)

使用 @types

处理外部库的新方法

要安装/使用 jquery ,您只需使用

将其安装到项目中
npm install --save @types/jquery

然后在 tsconfig.json 中,在类型下,相应​​地添加其引用,如图所示,

<强> 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"
    ]
  }
}

答案 2 :(得分:1)

首先,您不需要将其放在index.html中,而是将此条目放入angular-cli.json文件

像这样:

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

然后确保在使用之前正确安装了jQuery

同时检查根路径,同时在angular-cli.json文件中提供相对路径

答案 3 :(得分:1)

如果您使用webPack和Typescript,您可以执行以下操作:

您在vendor.ts文件中的

导入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";

然后在你的webpack.dev.js中使用插件将其导入每个组件,而无需手动导入:

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"
    }
};

现在代码中的任何地方.ts都可以像这样使用jquery:

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

    }

}

答案 4 :(得分:0)

我建议在现有@type的情况下遵循Nikhil Shah建议(如jQuery的情况)

但是如果您有导出全局变量的库(如jQuery)但没有已知的@type文件,您可以查看my following answer

答案 5 :(得分:0)

如果@tudorciotlos答案对您不起作用(例如我的情况),请尝试以下扩展方式:

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

Source here