How could I use a system.import() into component angular 2

前端 未结 2 1423
傲寒
傲寒 2021-01-17 12:51

I saw in this post that you can use SystemJS to load external javascript files into my components in Angular 2.

In my index.html :



        
相关标签:
2条回答
  • 2021-01-17 13:12

    You can use systemjs to do your external dependency loading.

    npm i systemjs --only=dev
    npm i @types/systemjs --only=dev
    

    You'll need to update your tsconfig.app.json file (tsconfig.json file for older versions of Angular).

    "types": ["systemjs"]
    

    Now you'll be able to import

    System.import("your-url").then(response => response.methodCall());
    

    If you have an import map specified

    <script type="systemjs-importmap">
     {
      "imports": {
        "import-name": "external-code-url",
      }
     }
    </script>
    

    You can instead call this code

    System.import("import-name").then(response => responce.methodCall());
    
    0 讨论(0)
  • 2021-01-17 13:15

    In fact, SystemJS is used under the hood when you import things. It's because you configured your TypeScript compiler to use it. See the tsconfig.json file:

    {
      "compilerOptions": {
        "target": "ES5",
        "module": "system",  <---------------
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      },
      "exclude": [
        "node_modules"
      ]
    }
    

    If you have a look at compiled JS files (these JS files are actually executed in the browser), you will see this:

    System.register(['angular2/platform/browser', 'angular2/http', './app.component'], function(exports_1) {
      var browser_1, http_1, app_component_1;
      return {
        setters:[
            function (browser_1_1) {
                browser_1 = browser_1_1;
            },
            function (http_1_1) {
                http_1 = http_1_1;
            },
            function (app_component_1_1) {
                app_component_1 = app_component_1_1;
            }],
        execute: function() {
            browser_1.bootstrap(app_component_1.AppComponent, [http_1.HTTP_PROVIDERS]).then(function (componentRef) {
                console.log(componentRef.injector);
            });
        }
      }
    });
    

    for a TypeScript file like this:

    import {bootstrap} from 'angular2/platform/browser';
    import {HTTP_PROVIDERS} from 'angular2/http';
    import {AppComponent} from './app.component';
    
    bootstrap(AppComponent, [ HTTP_PROVIDERS ]).then((componentRef) => {
      console.log(componentRef.injector);
    });
    
    0 讨论(0)
提交回复
热议问题