【问题标题】:In angular-cli, how does the "lazy" attribute work to load global libraries?在 angular-cli 中,“lazy”属性如何加载全局库?
【发布时间】:2017-05-26 11:27:24
【问题描述】:

通过将它们添加到 .angular-cli 文件的 scripts 属性中,可以将全局脚本加载到您的应用中。这个例子来自documentation

"scripts": [
  "global-script.js",
  { "input": "lazy-script.js", "lazy": true },
  { "input": "pre-rename-script.js", "output": "renamed-script" },
]

然而,我对“懒惰”属性有点困惑。在构建您的应用程序时,待延迟加载的脚本不再打包在 scripts.bundle.js 文件中。

但是到底如何加载库呢?必要时如何加载文件?

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

    作为 Will Huang 已接受答案的第 2 步中操作 DOM 的替代方法,现在还可以将 esnext 的动态导入功能与 TypeScript 一起使用,如 this post 中所述。

    使用这种方法,可以将以下内容添加到延迟加载的 NgModule:

    import('jquery')
        .then((module: Function) => {
            window['$'] = module;
        });
    

    【讨论】:

      【解决方案2】:

      如果您在.angular-cli.json 中配置“延迟”属性来加载全局库,则需要在需要时“延迟加载”脚本。以下是设置步骤。

      1.在apps[0].scripts数组中配置.angular-cli.json

      "scripts": [
          { "input": "../node_modules/jquery/dist/jquery.js", "output": "jquery", "lazy": true }
      ],
      

      您将在构建输出中获得一个jquery.bundle.js 文件。

      2.通过在DOM (<head>) 中延迟添加<script> 标签来加载生成的脚本。

      const script = document.createElement('script');
      script.src = 'jquery.bundle.js';
      script.type = 'text/javascript';
      script.async = true;
      script.charset = 'utf-8';
      document.getElementsByTagName('head')[0].appendChild(script);
      

      【讨论】:

      • 这非常有用:这样我们就可以延迟加载仅在延迟加载模块中使用的全局库。
      • 当 angular-cli 将您的 jquery.bundle.js 生成为 jquery.8ff49f9cee63643bea4a.bundle.js 时,我不确定这是否适用于输出哈希。
      • 感谢您的回答,这非常有效。 @mfink,当我们将输出指定为“jquery”时,生成的文件将始终为“jquery.bundle.js”
      • 快速更新到这个答案,在较新版本的 Angular 上,没有.bundle.js 输出,它只是yourlibraryname.js
      猜你喜欢
      • 2018-08-18
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      相关资源
      最近更新 更多