首页 > 解决方案 > 如何在不安装运行时导入其他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;

我期待警报“主题文本”。但没有回应。它说“未定义要求”,我发现它在客户端不起作用......

标签: javascript

解决方案


我看到你已经完成了

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

推荐阅读