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

别来无恙 提交于 2020-06-27 09:44:25

问题


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?


回答1:


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
});


来源:https://stackoverflow.com/questions/55310227/cant-figure-out-how-to-import-modules-in-browser-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!