【问题标题】:How to manage js files in angular如何以角度管理js文件
【发布时间】:2018-09-26 04:26:25
【问题描述】:

我正在开发一个 MEAN 应用,我的文件夹结构如下:

我在 /angular/src/assets/js 下添加了一个 js 文件用于一些 jQuery 的东西。

为此,我使用 npm 安装了 jQuery。

现在我需要通过angular.cli.json文件调用那个js文件。

angular.cli.json:

"apps": [
{
  "root": "angular/src",
  "outDir": "angular/dist",
  "assets": [
    "assets",
    "favicon.ico"
  ],
  "index": "index.html",
  "main": "main.ts",
  "polyfills": "polyfills.ts",
  "test": "test.ts",
  "tsconfig": "tsconfig.app.json",
  "testTsconfig": "tsconfig.spec.json",
  "prefix": "app",
  "styles": [
    "styles.css"
  ],
  "scripts": [
     "../node_modules/jquery/dist/jquery.min.js",
     "../src/assets/js/custom.js"
  ],

由于我将根指向“angular/src”,因此在位于“mean/node_modules/”下的脚本部分中包含 jquery.min.js 并以“未找到”错误结束时存在问题.

angular.cli.json 文件在“angular/src”根路径中查找“node_modules/jquery/dist/jquery.min.js”。

有什么方法可以在不改变我的文件夹结构的情况下解决这个问题?

需要别人的宝贵帮助。

【问题讨论】:

    标签: javascript jquery angular


    【解决方案1】:

    是的。从 angular.cli.json 中删除脚本链接,然后将其包含在带有脚本标记的 index html 中。

    效果很好。

    【讨论】:

      【解决方案2】:

      最简单的方法是直接在 index.html 中链接 js 文件。

      如果你想让它被angular编译维护,请查看这个链接

      How to include external js file in Angular 4 and call function from angular to js

      https://www.thepolyglotdeveloper.com/2016/01/include-external-javascript-libraries-in-an-angular-2-typescript-project/

      【讨论】:

      • 我也遵循同样的方法。我已经使用 npm 安装了 jquery。我已将它包含在 angular.cli.json 文件的脚本中。我还添加了“import * as $ from 'jquery';”在我的 component.ts 文件中。但仍然出现“$ 未定义”错误。
      • 您可能错过了添加类型。默认情况下,JQuery 不会有类型。所以角度编译器将不知道如何处理这些文件。参考这个链接angular.io/guide/typescript-configuration
      猜你喜欢
      • 2018-07-09
      • 2016-10-26
      • 2015-09-10
      • 1970-01-01
      • 2021-07-02
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多