【问题标题】:angular 2 referencing external js file in index.htmlangular 2 在 index.html 中引用外部 js 文件
【发布时间】:2017-05-13 13:49:09
【问题描述】:

我正在使用 angular cli 工具制作一个简单的 angular 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 中?感谢您的帮助。

【问题讨论】:

  • 嗨.. 你也在使用 webpack 吗? ..还有打字稿?
  • @fscamuzzi81 是的,我正在使用 typescript 和 webpack。

标签: angular


【解决方案1】:

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

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

之后,如果ng serve已经启动,则重启它。

【讨论】:

  • 非常感谢都铎王朝。简短、简单、中肯的答案!
【解决方案2】:

首先你不需要把它放在 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】:

    有一种使用 @types

    处理外部库的新方法

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

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

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

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

    【讨论】:

    • 使用这种方式有什么好处?我的意思是使用@types
    • 之前没有管理外部库的机制,但现在只在一个文件中使用类型就可以管理外部库...
    • 哪一个文件?如果您提供与该机制相关的任何链接会更有帮助,顺便说一句谢谢:)
    • 不幸的是,我认为没有任何官方文档可用于相同的内容,但请看这里-angular.io/docs/ts/latest/guide/typescript-configuration.html 并为我搜索它。我会很容易得到东西。
    • 非常感谢 micronyks 的解决方案。我现在没有尝试,但我会看看它。
    【解决方案4】:

    如果你使用 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);
    
        }
    
    }
    

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        【解决方案6】:

        如果@tudorciotlos 的回答对你不起作用(比如我的情况),请尝试这种扩展方式:

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

        Source here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-24
          • 1970-01-01
          • 2016-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-23
          • 1970-01-01
          相关资源
          最近更新 更多