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?
3 Answers 3
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.
-
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– Steve2016年01月03日 14:19:36 +00:00Commented Jan 3, 2016 at 14:19
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;
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?