In angular-cli, how does the “lazy” attribute work

2020-03-04 07:43发布

问题:

By adding them to the scripts property of .angular-cli file, one can load global scripts into your app. This example comes from the documentation:

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

I am however a bit confused by the "lazy" attribute. When building your app, the to-be-lazy-loaded script is no longer packaged in the scripts.bundle.js file.

But how will the library then be loaded after all? What do I have to do to load the file when necessary?

回答1:

If you configure the "lazy" attribute in the .angular-cli.json to load global libraries, you need to "lazy load" the script when needed. Here is the steps to setup.

1.Configure .angular-cli.json in the apps[0].scripts array.

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

You'll get an jquery.bundle.js file in the build output.

2.Load the generated script by appending <script> tag in the DOM (<head>) lazily.

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


回答2:

As an alternative to manipulating the DOM in step #2 of Will Huang's accepted answer, it's now also possible to use the dynamic import functionality of esnext with TypeScript, as outlined in this post.

Using this approach, one could then add the following to a lazy-loaded NgModule:

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