Can ES6's module loader also load assets (html/css/...)

If you use SystemJS then you can load assets by using plugins:

// Will generate a <link> element for my/file.css
System.import('my/file.css!')
    .then(() => console.log('CSS file loaded'));

Alternatively, you can use an import statement. This will make sure that the CSS file is loaded before the your script executes:

import 'my/file.css!';

Finally, you can retrieve the contents of the file using the text plugin:

import cssContent from 'my/file.css!text';
console.log('CSS file contents: ', cssContent);

Another option is to add the css as a dependency in JSPM config files. Basically adding the dependency in the specific package .json file and then running 'jspm install' which will add the override to package.js & jspm.config.js


I know you mentioned ES6 modules, but as that does not appear to support CSS natively, if you're looking for something standards-based to load resources dynamically and wish for something possibly somewhat less unpleasant than XMLHttpRequest, the new Fetch API might be used like this:

var myStylesheets = ['myStyles1.css', 'myStyles2.css'];

Promise.all(myStylesheets.map(url => fetch(url))).
    then(arr => Promise.all(arr.map(url => url.text()))).
    then(arr => {
        var style = document.createElement('style');
        style.textContent = arr.reduce(
            (prev, fileContents) => prev + fileContents, ''
        );
        document.head.appendChild(style);
    }).then(() => {
        // Do whatever now
    });

This is even cleaner with async functions:

var myStylesheets = ['myStyles1.css', 'myStyles2.css'];

async function loadStyles(stylesheets) {
    let arr = await Promise.all(stylesheets.map(url => fetch(url)))
    arr = await Promise.all(arr.map(url => url.text()))
    const style = document.createElement('style')
    style.textContent = arr.reduce(
        (prev, fileContents) => prev + fileContents, ''
    )
    document.head.appendChild(style);
    // Do whatever now
}

loadStyles(myStylesheets)

For other resource types, you can use the blob() method for images, and pending ES6 modules support, eval() for JavaScript, etc.