简体   繁体   English

无法弄清楚如何使用JavaScript在浏览器中导入模块

[英]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. 我正在尝试将模块从一个javascript文件导入到另一个文件,然后在Chrome上运行它。 I'm using 2 javascript files and an html file, all in the same folder: 我正在使用2个javascript文件和一个html文件,它们都位于同一文件夹中:

first js file (testfile1.js): 第一个js文件(testfile1.js):

import {test} from 'testfile2.js';

test.func();

second js file (testfile2.js): 第二个js文件(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: 该html文件是纯净的空html文件,在标题中带有testfile1.js脚本的链接:

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

Whenever I open the html file in chrome, I get the error: 每当我在chrome中打开html文件时,都会收到错误消息:

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" 模块需要type="module"而不是"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. 根据Jaromanda X的评论,您需要将<script>标记的type属性的值更改为"module"因为import { test } from 'testfile2.js'是模块代码。

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

What about dynamic import() 那么动态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" . 如果您真的不想使用type="module" ,则即使没有type="module" ,任何javascript文件都可以使用动态import()语法。

However, the dynamic import has a caveat, the function import() returns a promise, therefore, you are unable to use it synchronously. 但是,动态导入有一个警告,函数import()返回一个promise,因此,您将无法同步使用它。 You must either await or .then a dynamic import to use the value it resolves to. 您必须await.then动态导入才能使用解析后的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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