ES module import not working

前端 未结 2 1052
抹茶落季
抹茶落季 2021-01-19 18:19

I am trying to make simple example of vanilla ES import export.

index.js




  

        
相关标签:
2条回答
  • 2021-01-19 18:27

    import needs a fully qualified URL. You can't leave off the extension unless the absolute URL doesn't have an extension on it.

    So judging by your examples use:

    import {foo} from './mathModule.js';
    

    As Nimeshka Srimal caught, it looks like the extension requirement varies between implementations. Firefox is appending .js automatically, but Chrome and Safari expect the actual address.

    I'm looking at the spec, 15.2.2 Imports, and there doesn't seem to be any specification on whether the implementer should append the extension automatically or not.

    Additionally, as ASDFGerte pointed out from the MDN docs on import:

    The module to import from. This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single quotes and double quotes Strings are allowed.

    0 讨论(0)
  • 2021-01-19 18:31

    The simplest would be to remove the export and import expressions since you're already including both files in your html.

    const foo = Math.sqrt(2) // mathModule.js
    console.log(foo) // main.js
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8" />
      <script src="mathmodule.js"></script>
      <script src="main.js"></script>
    </head>
    <body>
    
    </body>
    </html>

    If you are using node or something similar to run the script, maybe you should use a transpiler such as babel. Import and Export are "new" javascript features hence they're not implemented in most browsers

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