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

前端 未结 2 1226
时光说笑
时光说笑 2020-12-24 01:09

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 <

相关标签:
2条回答
  • 2020-12-24 01:45

    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

    0 讨论(0)
  • 2020-12-24 02:04

    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.

    0 讨论(0)
提交回复
热议问题