简体   繁体   中英

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?

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

As per Jaromanda X's comment, you need to change the value of the type attribute of the <script> tag to "module" as 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM