How to call a named module from a bundle

℡╲_俬逩灬. 提交于 2019-12-11 12:26:05

问题


I have a project with ASP.NET 5 and TypeScript. basically this is my wwwroot folder

-wwwroot
|-app
||-person.js
||-employee.js
||-init.js
|-js
||-libraries.js    // Contains: systemjs, ...etc
||-app.bundle.js

person.js is an es6 module which exports class Person.

employee.js imports person.js and exports class Employee.

init.js just imports employee.js, creates a new Employee object and console his name.

//init.js
import { Employee } from "./employee";

var p = new Employee();
console.log(p.name);

Now I bundled the three files into app.bundle.js which is located in the js folder using systemjs-builder which produced three named System.register calls:

System.register("wwwroot/app/person.js",...
System.register("wwwroot/app/employee.js",...
System.register("wwwroot/app/init.js"...

In my index.cshtml view file I have these script tags:

<script type="text/javascript" src="./js/libraries.js"></script>

<!-- 2. Configure SystemJS -->
<script type="text/javascript">
    System.config({
        packages: {
            js: {
                format: 'register',
                defaultExtension: 'js'
            }
        }
    });
    System.import('js/app.bundle')
        .then(null, console.error.bind(console));
</script>

apparently since I have named modules, whatever is in the init.js is not being called.

So my question is, how can I call a named System.register call ?

Note: I am new to es6 modules, so this is a test project to get the idea right.


回答1:


From this wiki page, I solved my problem with this:

<script type="text/javascript">
    System.config({
        bundles: {
            'app.bundle.js': ['wwwroot/app/init']
        },
        packages: {
            wwwroot: {
                format: 'register',
                defaultExtension: 'js'
            }
        }
    });
    System.import('wwwroot/app/init')
        .then(null, console.error.bind(console));
</script>

To explain:

The bundle extension will automatically download a bundle as soon as an attempt to import any module in that bundle is made.

So all I need to do is to tell systemjs to register the init module to my bundle and it will download the bundle and execute whatever is in the init module.



来源:https://stackoverflow.com/questions/34387957/how-to-call-a-named-module-from-a-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!