Search code examples
javascriptmodulees6-modules

Can't figure out how to import modules in browser with javascript


This is a simple problem. I'm attempting to import modules from one javascript file to another, and then run it on Chrome. I'm using 2 javascript files and an html file, all in the same folder:

first js file (testfile1.js):

import {test} from 'testfile2.js';

test.func();

second js file (testfile2.js):

let f = function() {
  console.log("TEST");
}

let test = {
  func: f
};

export test;

The html file is plain, empty html file with a link to testfile1.js script in the header:

<script type="text/javascript" src="testfile1.js"></script>

Whenever I open the html file in chrome, I get the error:

testfile1.js:1 Uncaught SyntaxError: Unexpected token {

When I removed the brackets in the import statement, I get an unexpected identifier statement. Isn't this the proper way to import modules in the browser? Why is it not working at all?


Solution

  • Modules require type="module" not "text/javascript"

    As per Jaromanda X's comment, you need to change the value of the <script> tag's type attribute to "module" because import { test } from 'testfile2.js' is module code.

    <script type="module" src="testfile1.js" />
    

    What about dynamic import()

    If you really don't feel like using type="module", any JavaScript file is allowed to use the dynamic import() syntax, even without type="module".

    However, the dynamic import has a caveat; the function import() returns a promise, therefore, you are unable to use it synchronously. You must either await or .then a dynamic import to use the value it resolves to.

    import('testfile2.js').then(({ test }) => {
      // your code
    });