Are these two lines the same?
var myModule = new require('my-module')
and:
var myModule = require('my-module')
The former helps intelliJ Idea (or Webstorm) to do autocompletion on methods (e.g "model" in mongoose) (at least it doesn't show the annoying yellow underline that says "Unresolved function or method"
require() is used to consume modules. It allows you to include modules in your app. You can add built-in core Node. js modules, community-based modules (node_modules), and local modules too.
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).
To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.
require
.new
should be used when you're instantiating a new instance of a class or function, and not otherwise. You almost certainly don't want to instantiate an instance of require
.
However, if you want to instantiate an instance of a class/function returned by require
, you could probably do something like:
var myModuleInstance = new (require('my-module'));
The extra containing parentheses means you're instantiating the returned object, not directly instantiating require
.
In terms of JavaScript, they're not the same. In terms of require()
as a function? It seems so, but I'd still advise against doing it.
Using new
does a lot under the hood. require()
will be affected by the use of new
, as it's internal value of this
will change.
var foo = {
path: '/foo/bar/',
require: function (module) {
console.log(this.path + module);
}
};
foo.require('baz'); // logs /foo/bar/baz
new foo.require('trev'); // logs undefinedtrev
Currently require()
seems not to use this
at all (as it's behaviour doesn't change whether you change the value of this or not). However, this isn't guaranteed to be the case in the future; it isn't documented.
TL;DR: don't use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With