Javascript module not working in browser?

前端 未结 8 1825
半阙折子戏
半阙折子戏 2020-12-10 11:35

Alright, I have looked on this site and have found several different answers, none of which have worked for me. Basically had a js file that had many functions in it along

8条回答
  •  有刺的猬
    2020-12-10 12:26

    JavaScript has had modules for a long time. However, they were implemented via libraries, not built into the language i.e. you can't import or export part of those modules into your js files (whole library needs to be loaded). ES6 is the first time that JavaScript has built-in modules.

    Please refer Here for more info about ES modules.

    But things have changed and ES modules are now available in browsers! They're in…

    Safari 10.1+, Chrome 61+, Firefox 60+, Edge 16+, etc,.

    Now, you need to create your JS file using a new extension .mjs, like,

    // utils.mjs
    export function addTextToBody(text) {
      const div = document.createElement('div');
      div.textContent = text;
      document.body.appendChild(div);
    }
    

    and then, you can import that file into your html page like,

    
    

    Please refer Here for more info about using ES module in browsers.

提交回复
热议问题