简体   繁体   English

在纯.js文件中添加对Javascript文件的引用

[英]Adding Refernce to a Javascript file in a plain .js file

I want to create a SignalR client in JavaScript. 我想用JavaScript创建SignalR客户端。 Am not using any HTML files(its not a web application).My intention is to create ".js" file and connect to the SignalR hub and subscribe to the events,and when the events got triggered I want to output the data to a console. 我不使用任何HTML文件(不是Web应用程序)。我的意图是创建“ .js”文件并连接到SignalR集线器并订阅事件,当事件被触发时,我想将数据输出到安慰。 So how can I refer "signalR-2.1.0.min.js" in my plain .js file. 因此,如何在我的纯.js文件中引用“ signalR-2.1.0.min.js”。

<script src="Scripts/signalR-2.1.0.min.js"></script>

The above way of reference works only with HTML files.This is working fine in my web application. 上面的引用方式仅适用于HTML文件,这在我的Web应用程序中很好用。 But if I want to run a ".js" file for the same purpose (as a SignalR client without html files)how can I add reference to this "signalR-2.1.0.min.js" file? 但是,如果出于相同目的(例如不带html文件的SignalR客户端)运行“ .js”文件,如何添加对该“ signalR-2.1.0.min.js”文件的引用?

Thanks In Advance Susmitha 在此先感谢Susmitha

如果您使用的是Node.js,则可以使用require:

const myFile = require('./myScript.js');

okay, so there are two methods, depending on whether your using server-side (Node) or just ordinary client-side JavaScript. 好的,所以有两种方法,具体取决于您使用的是服务器端(节点)还是仅使用普通的客户端JavaScript。

Server-side JavaScript 服务器端JavaScript

Like was mentioned in the other answer by DoeDoeDoe , you can use require() which is built-in to Node.js. 就像在DoeDoeDoe另一个答案中提到的那样 ,您可以使用Node.js内置的require()

const signalR= require('./Scripts/signalR-2.1.0.min.js');

Client-side JavaScript 客户端JavaScript

Out-of-the-box, this is not possible with ordinary client-side JavaScript. 开箱即用,这对于普通的客户端JavaScript是不可能的。 However there are a few alternatives: 但是,有几种选择:

jQuery jQuery的

$.getScript("/Scripts/signalR-2.1.0.min.js", function(){
   console.log('Got the script!');
});

Browserify Browserify

With Browserify you can use the node-style require , client-side. 借助Browserify,您可以使用节点风格的require ,客户端。 However it needs to be compiled each time before you can run it. 但是,每次运行之前都需要对其进行编译。 Basically what happens is that all the modules and scripts that you require, get injected into the final single-page script. 基本上发生的是,您需要的所有模块和脚本都被注入到最终的单页脚本中。 Allowing them to be utilised by the other code in that file. 允许它们被该文件中的其他代码利用。

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

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