我对此很困惑。我只想将我的 javascript 分解成模块,并将它们包含在某些页面中。有些页面可能需要我的 user-module.js ,有些页面可能不需要。
我用 Google 搜索过,阅读了教程,但它仍然不适合我。
这是一个简单的测试用例:
<强>1。从我的 html 中包含我的脚本
<script src="../js/login-view-model.js"></script>
现在,里面...
<强>2。尝试包含另一个模块/js 文件
// LoginViewModel
// I NEED MY IMPORT HERE
import { userService } from '../js/viewModels/user-service.js'
var LoginViewModel = function () {
self = this;
userService.user.sayHello();
}; // End View Model
ko.applyBindings(new LoginViewModel());
现在,在我的 user-service.js 中
user-service.js
let user = {
sayHello: function() { alert("hello") };
}
export {user};
我看不出我错过了什么。
我是否需要使用另一个 JS 库才能让这个简单的示例正常运行?我迷路了...大声笑,请帮忙!
哦,如您所见,我正在使用 KnockoutJS。不确定这是否是问题所在。
谢谢。
约翰
最佳答案
(在 jsfiddle 之类的东西中并没有很好的方法来展示如何做到这一点,所以我对内联代码表示歉意)
这是您尝试执行的操作的一个非常基本的示例(减去 knockout 部分)
这里的一个关键是您需要告诉浏览器您的脚本是一个模块 (type="module"
)(请参阅 ES6 in the browser: Uncaught SyntaxError: Unexpected token import 以了解在未定义时可能遇到的其他一些问题类型
作为模块
)
解决问题的另一个关键是您试图以错误的方式调用 .sayHello()
。
userService.user.sayHello(); // wrong
userService.sayHello(); // right
你exported
用户所以你不需要做.user
,你导出的对象上没有user
的属性。 userService
已经是 user
工作示例:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="loginviewmodel.js" type="module"></script>
</body>
</html>
查看模型
import { user } from "./userservice.js";
user.sayHello();
用户服务
let user = {
sayHello: function() { alert("hello"); }
};
export {user};
关于javascript - 如何让 Javascript 的 IMPORT EXPORT 工作。我需要转译器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56959001/