Can es6's module loader also load assets (html/css/…)

对着背影说爱祢 提交于 2019-11-28 18:43:44

问题


ES6's modules are based on a flexible loader architecture (although the standard is not final, so ...).

Does this mean ES6's loader, based on system.js, can load all assets? I.e. CSS, HTML, Images, Text, .. files of any sort?

I ask because I'm starting to use WebComponents & Polymer which have their own HTML import, and implementing them with ES6, which has its own import/loader (system.js).


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/24923479/can-es6s-module-loader-also-load-assets-html-css

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