3.2 KiB
Module Types
Both system.js and s.js support loading javascript modules, json modules, and css modules.
Limitations
The browser spec calls for checking a module's mime type to know whether it is JSON, CSS, or Javascript. SystemJS does not do that, since it has to choose upfront whether to append a script element (for js modules) or make a fetch request (for a JSON/CSS module). So instead of the mime type, the file extension is used to determine the type of the module.
Javascript modules
SystemJS supports loading javascript modules that are in the following formats:
| Module Format | s.js | system.js |
|---|---|---|
| System.register | ✔️ | ✔️ |
| Global variable | global extra | ✔️ |
| ESM | transform extra | transform extra |
| AMD | AMD extra | AMD extra |
| UMD | AMD extra | AMD extra |
JSON Modules
JSON modules are supported in both s.js and system.js.
Example
file.json
{
"some": "json value"
}
System.import('file.json').then(function (module) {
console.log(module.default); // The json as a js object.
});
CSS Modules
CSS Modules are supported in both s.js and system.js, when a Constructable Style Sheets polyfill is present for browsers other than Chromium.
Note that the term CSS Modules refers to two separate things: (1) the browser spec, or (2) the webpack / postcss plugin. The CSS modules implemented by SystemJS are the browser spec.
Example
/* file.css */
.brown {
color: brown;
}
System.import('file.css').then(function (module) {
const styleSheet = module.default; // A CSSStyleSheet object
document.adoptedStyleSheets = [...document.adoptedStyleSheets, styleSheet]; // now your css is available to be used.
});
Constructable Style Sheets Polyfill
CSS modules export a Constructable Stylesheet instance as their default export when imported.
Currently these are only available in new versions of Chromium based browsers (e.g., Chrome 73+), so usage in any other browsers will require a polyfill, such as the one at https://www.npmjs.com/package/construct-style-sheets-polyfill.
Note that this polyfill does not currently work in IE11.
The polyfill can be conditionally loaded with an approach like:
<script src="system.js"></script>
<script>
try { new CSSStyleSheet() }
catch (e) {
document.head.appendChild(Object.assign(document.createElement('script'), {
src: 'https://unpkg.com/browse/construct-style-sheets-polyfill@2.1.0/adoptedStyleSheets.min.js'
}));
}
</script>
If the polyfill is not included, CSS modules will not work in other browsers.