简体   繁体   中英

Adding Refernce to a Javascript file in a plain .js file

I want to create a SignalR client in JavaScript. 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. So how can I refer "signalR-2.1.0.min.js" in my plain .js file.

<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. 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?

Thanks In Advance 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.

Server-side JavaScript

Like was mentioned in the other answer by DoeDoeDoe , you can use require() which is built-in to Node.js.

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

Client-side JavaScript

Out-of-the-box, this is not possible with ordinary client-side JavaScript. However there are a few alternatives:

jQuery

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

Browserify

With Browserify you can use the node-style require , client-side. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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