1

Running a node.js app provides a means to load an included js script as a class/variable.

--- app.js ---

var mine = require('myClass');
mine.DoSomething();

How does node know that MyClass is the file "js/MyClassFile.js"?
What is the HTML <script> equivalent?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Steve
  • 905
  • 1
  • 8
  • 32

3 Answers3

1

It use something called modules. For example in js/MyClassFile.js there must be something like

exports.myClass = function (r) { return {DoSomething: function(){} }; };

What is the HTML equivalent?

If by html, you mean browser, then there is options like browserify, systemjs, requirejs, etc, etc

for more info check Writing Modular JavaScript With AMD, CommonJS & ES Harmony by Addy Osmani out.

R Pasha
  • 700
  • 5
  • 21
  • That is pretty much what I was expecting to hear. The makers of this js script I'm trying to use didn't build it for straight html. It looks like they started a build of it but then abandoned what I want, didn't mention so in the documentation, and then implemented it in node where the whole concept works as an app. – Steve Jan 03 '16 at 14:19
0

When you require a file in say app.js, you should use its relative path and export it using module.exports. That's how Node.js knows where to look for it.
--- app.js ---

var mine = require('../myClass')
mine.doSomething();


--- myClass.js ---

var myClass = {
}
module.exports = myClass;
noonkay
  • 123
  • 7
0

How does node know that MyClass is the file "js/MyClassFile.js"?

Node decides it on basis of relative path so if you are in js folder and try to use var mine = require('myClass'); then it means then myClass is in js folder

for html equivalent you need to use modules but you can do it in es6 like this, please note es6 support is still limited

//  lib/math.js 
export function sum (x, y) { return x + y } 
export var pi = 3.141593

//  someApp.js 
import * as math from "lib/math" 
console.log("2π = " + math.sum(math.pi, math.pi))

//  otherApp.js 
import { sum, pi } from "lib/math" 
console.log("2π = " + sum(pi, pi)) 

otherwise you can look at this How do I include a JavaScript file in another JavaScript file?

Community
  • 1
  • 1
Raunak Kathuria
  • 3,185
  • 1
  • 18
  • 27