import not working in Chrome

后端 未结 2 1074
时光取名叫无心
时光取名叫无心 2020-12-16 14:51

I am creating an single page app in vanilla JavaScript. I want to organize my code in different files to make it modular, which means I should be able to access functions de

2条回答
  •  醉梦人生
    2020-12-16 15:47

    Here is a working example

    file1.mjs

    function log1() {
      console.log('log1');
    }
    function log2() {
      console.log('log2');
    }
    export { log1, log2 };
    

    file2.mjs you must explicitly write .mjs extension

    import { log1, log2 } from './file1.mjs';
    
    log1();
    log2();
    

    index.html Notice attribute type="module"

    
        
    
    

    Then you need a static server to get rid of CORS block.

    $ yarn global add serve
    $ serve ./
    

    Finally go to http://localhost:5000 and it will work

    Update: It is recommended to use .mjs file extension for modules instead of .js

提交回复
热议问题