javascript - 如何在不安装运行时导入其他js文件
问题描述
我想在 JS 文件中使用类声明而不安装运行时(希望是纯 JS 或像纯的)。
看起来有一种方法可以安装运行时和“从 filename.js 导入 xxx”。但我无权在服务器上安装。我也尝试使用 babel-standalone 来使用 require()。
尝试 babel-standalone 使用 require()
两者直接相同
应用程序.js
消息.js
应用程序.js
mes = require("message.js");
mes.notice();
消息.js
class message {
constructor(subject, text) {
this.subject = "subject";
this.text = "text";
}
notice() {
alert(this.subject + '\n' + this.text);
}
}
const mes = new message();
module.exports = mes;
我期待警报“主题文本”。但没有回应。它说“未定义要求”,我发现它在客户端不起作用......
解决方案
我看到你已经完成了
const mes = new message();
但是,您的消息类有一个构造函数,它接受参数主题和文本。你是不是打算做
const mes = new message("A subject", "A text");
在客户端javascript中,您不能使用“require”。相反,你可以做这样的事情(html)。
<script>
class message {
constructor(subject, text) {
this.subject = "subject";
this.text = "text";
}
notice() {
alert(this.subject + '\n' + this.text);
}
}
const mes = new message();
</script>
<script>
mes.notice();
</script>
没有必要使用require。即使有两个不同的脚本标签,您仍然可以访问全局变量。
更新: 你可以做的是有另一个脚本标签
<script src="message.js">
var notice = function(mes){
mes.notic();
}
</script>
Then whenever you need to 'notice' a message from the other script (app.js), you can just call notice(message);
推荐阅读
- android - Nativescript 错误:构建失败。仅支持 8、16、24 或 32 位:872
- javascript - 如何克隆 div 值以输入
- docker - 在docker容器内构建Jenkins-job后如何从ROOT所有权更改为jenkins
- gradle - Gradle 版本解析问题:构建 Xcore
- c# - Unity 检查 Toggle 是否开启
- javascript - 使用 for 循环、if else 语句和增量的倍数重构函数
- python - 使用 pipenv 添加 python 项目
- c# - 如何在 Unity 中为全局类创建别名?
- angular - Angular,在鼠标事件上用画布绘制多个矩形
- php - 有条件订阅 Laravel 中的侦听器