在index.html中引用外部js文件的angular 2

7

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

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

似乎不起作用:

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

如何确保jquery.js被包含在index.html中? 感谢任何帮助。


嗨..你也在使用webpack吗?还有typescript吗? - federico scamuzzi
@fscamuzzi81 是的,我正在使用TypeScript和Webpack。 - tempx
6个回答

6
为了包含一个全局库,您需要在angular-cli.json文件中的“scripts”数组中添加jquery.js文件:
"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

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


非常感谢您,Tudor。简短、简单而直接的回答! - tempx

4

使用@types,有一个新的处理外部库的方法。

要安装/使用jquery,您只需要在项目中安装它即可:

npm install --save @types/jquery

tsconfig.json 中的 types 下,根据以下示例相应地添加其引用。
{
  "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"
    ]
  }
}

使用这种方式有什么好处?我的意思是使用 @types - Pardeep Jain
以前没有机制来管理外部库,但现在只需在一个文件中使用类型即可管理您的外部库... - micronyks
哪个文件?如果您提供相关机制的链接,将更有帮助。顺便说一句,谢谢 :) - Pardeep Jain
1
不幸的是,我认为没有任何官方文档可用于此,但请看这里 - https://angular.io/docs/ts/latest/guide/typescript-configuration.html,并为我谷歌一下。我会很容易地获取这些信息。 - micronyks
非常感谢您的解决方案,micronyks。我现在还没有尝试过,但我会看一下的。 - tempx

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文件中给出相对路径时,请检查根路径


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

    }

}

0

如果存在@type(例如jQuery的情况),我建议遵循Nikhil Shah的建议。

但是,如果您有一个导出全局变量(如jQuery)但没有已知@type文件的库,则可以查看我的下面的答案


0

如果@tudorciotlos的回答对你没有用(就像我的情况一样),请尝试这种扩展方式:

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

     <script src="renamed-script.js"></script>

此处放置源代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接