Using SystemJS/jspm to load async, es5 modules in production

倖福魔咒の 提交于 2019-12-10 02:26:34

问题


I want to be able to asynchronously load dependencies using System.import(), but without having to transpile ES6 to ES5 during production runtime. I want these modules to be transpiled into separate, ES5 modules that are fetched only when needed. I don't want them to be a part of the main bundle.

Dev Workflow

The modules are effectively loading during my production build which is actually worrisome because I don't want to include any dependencies that allow for transpilation.

I have a workflow where I'm using jspm bundle and jspm unbundle to toggle between development and production configurations. In my development environment, I'm including the following scripts:

<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>

<script>
    System.import('src/main');
</script>

Production Workflow

In production, I'm using jspm bundle --inject to inject the bundles option into System.config. This effectively loads only the necessary files:

system.js
config.js
main.bundle.js

When I try to load a module asynchronously with System.import() during production, it loads fine, which means that transpilation is happening in the browser during production.


Questions

  1. I can easily build each of my modules into AMD, but how can I still asynchronously and separately fetch them using System.import()?

  2. I also want to make sure to include as little browser overhead as possible, which means not including any scripts that perform transpilation. Is there a way to include system.js that does not have transpile capabilities?


回答1:


Answer 1

System.import() is used for loading modules. Modules are essential .js files that export something such as a function or an Object or a Class.

If you organise your code into separate files then you can load them either in the head of another file using ..

import * as YM from 'YourModuleFile';

this would make YM accessible in the entire file.

Or if you want YM loaded on a button click instead ..

element.onclick = function() {
    System.import('YourModuleFile').then(function(YM) {
        // YM accessible here
    })
}

So the important thing becomes organising your code well inside files / modules.

You then might use an npm task runner such as gulp to compress the files, etc.

Of course, you will need to enter some mappings inside your systemjs.config.js file such as ..

'YourModuleFile': '/path/to/your/module/file.js'

So that SystemJS can find it.

Answer 2

JSPM has tranpile capabilities, I'm not sure SystemJS does.

Ensure JSPM (or your tool of choice) transpiles your files. Then point SystemJS to the transpiled files.



来源:https://stackoverflow.com/questions/36018965/using-systemjs-jspm-to-load-async-es5-modules-in-production

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