无法弄清楚如何使用 javascript 在浏览器中导入模块
Can't figure out how to import modules in browser with javascript
这是一个简单的问题。我正在尝试将模块从一个 javascript 文件导入到另一个文件,然后 运行 它在 Chrome 上。我正在使用 2 个 javascript 文件和一个 html 文件,它们都在同一个文件夹中:
第一个 js 文件 (testfile1.js):
import {test} from 'testfile2.js';
test.func();
第二个 js 文件 (testfile2.js):
let f = function() {
console.log("TEST");
}
let test = {
func: f
};
export test;
html 文件是普通的空 html 文件,在 header:
中有一个 link 到 testfile1.js 脚本
<script type="text/javascript" src="testfile1.js"></script>
每当我打开 chrome 中的 html 文件时,我都会收到错误消息:
testfile1.js:1 Uncaught SyntaxError: Unexpected token {
当我删除导入语句中的括号时,我得到了一个意外的标识符语句。这不是在浏览器中导入模块的正确方法吗?为什么它根本不起作用?
模块需要 type="module"
而不是 "text/javascript"
根据 Jaromanda X 的评论,您需要将 <script>
标记的 type
属性的值更改为 "module"
,因为 import { test } from 'testfile2.js'
是模块代码。
<script type="module" src="testfile1.js" />
动态呢import()
如果您真的不想使用 type="module"
,任何 javascript 文件都可以使用动态 import()
语法,即使没有 type="module"
.
但是,动态导入有一个警告,函数import()
returns 是一个promise,因此,您无法同步使用它。您必须 await
或 .then
动态导入才能使用它解析为的值。
import('testfile2.js').then(({ test }) => {
// your code
});
这是一个简单的问题。我正在尝试将模块从一个 javascript 文件导入到另一个文件,然后 运行 它在 Chrome 上。我正在使用 2 个 javascript 文件和一个 html 文件,它们都在同一个文件夹中:
第一个 js 文件 (testfile1.js):
import {test} from 'testfile2.js';
test.func();
第二个 js 文件 (testfile2.js):
let f = function() {
console.log("TEST");
}
let test = {
func: f
};
export test;
html 文件是普通的空 html 文件,在 header:
中有一个 link 到 testfile1.js 脚本<script type="text/javascript" src="testfile1.js"></script>
每当我打开 chrome 中的 html 文件时,我都会收到错误消息:
testfile1.js:1 Uncaught SyntaxError: Unexpected token {
当我删除导入语句中的括号时,我得到了一个意外的标识符语句。这不是在浏览器中导入模块的正确方法吗?为什么它根本不起作用?
模块需要 type="module"
而不是 "text/javascript"
根据 Jaromanda X 的评论,您需要将 <script>
标记的 type
属性的值更改为 "module"
,因为 import { test } from 'testfile2.js'
是模块代码。
<script type="module" src="testfile1.js" />
动态呢import()
如果您真的不想使用 type="module"
,任何 javascript 文件都可以使用动态 import()
语法,即使没有 type="module"
.
但是,动态导入有一个警告,函数import()
returns 是一个promise,因此,您无法同步使用它。您必须 await
或 .then
动态导入才能使用它解析为的值。
import('testfile2.js').then(({ test }) => {
// your code
});