【问题标题】:How to load other file(s) before Angular2 components如何在 Angular 2 组件之前加载其他文件)
【发布时间】:2017-01-31 10:12:05
【问题描述】:

是否可以在 Angular 2 加载之前加载某个文件?目前我在angular-cli.json 中全局加载jQuery, bootstrap, file.js,包括它,当你启动Angular 时,它会捆绑在一起。

是否可以在 Angular 之前先加载 file.js?我还需要为此 file.js 加载 jQuery,因为它有一些 jQuery http 请求。我尝试将 ../node_modules/jQuery 从 angular-cli.json 移动到我的 index.html。

Angular-cli.json - 当 file.js 在 angular-cli.json 中时

"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js",
    "./assets/js/file.js"
  ],

index.html - 当我在索引中移动 jQuery 和 file.js 时,我发现 jQuery 没有定义。

// in head tag
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.js"></script>
<script src="./assets/js/config/env.js"></script>

【问题讨论】:

  • 有什么理由不能将 file.js 捆绑为外部文件?在 angular CLI 中,您可以通过将 file.js 放入 angular-cli.json 文件的“scripts”数组中来完成此操作。看这里:tcoz.com/newtcoz/#/errata 并转到“在 Angular 2 (CLI) 中使用外部脚本”。
  • 是的,目前我将它捆绑在 angular-cl.jsoni 中,但是我需要在我的组件之前先加载 file.js。
  • @MrNew 在启动脚本之前导入库,否则它不会自行注册。
  • @RomanC 看看下面的对话,你能举个例子吗?

标签: javascript jquery twitter-bootstrap angular


【解决方案1】:

在要使用jQuery($) 的.ts 文件顶部,导入以下内容:

import $ from 'jquery';

现在您可以将$ 用于jquery 相关的事情。

【讨论】:

  • 我可以将其用作全局而不是将其放入某个 .ts 中吗?
  • 使用typings 全局安装可能但不确定。如果你发现任何类似的东西,请告诉我。
  • 我需要在 index.html 中的 file.js 之前加载 jquery,以便 $ajax 工作。所以我不确定在 .ts 中导入 $ 是否可行。也许我需要像往常一样加载文件。
  • 我试过了,在typings.ts中添加了declare $: JQueryStatic,但没有用。
猜你喜欢
  • 2016-04-04
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
相关资源
最近更新 更多