NodeJS - How to assign module.exports to a self-executing constructor?

I am trying to assign a constructor in a self-executing function in NodeJS. I am sure that it does not work because my parameter is a variable pointing to module.exports, but I am curious if there is a way to make it work as close as possible to a self-executing format.

Here, how the code is called ...

var TemplateEngine = require('./templateEngine'); templateEngine = new TemplateEngine({engine: 'swig'}); // "object is not a function" 

Here is a sample code that works great ...

 var assert = require('assert'); var swig = require('swig'); // Constructor var TemplateEngine = function(args) { assert.ok(args.engine, 'engine is required'); var templateEngine = {}; templateEngine.engine = args.engine; templateEngine.Render = function(templateString, model) { var result = swig.render(templateString, model); return result; }; return templateEngine; }; module.exports = TemplateEngine; 

and here is an example of a code style that I would like to use, but which raises the error “TypeError: Object is not a function”, because I actually do not assign module.exports, just a variable that copied it all pointed to.

 (function(templateEngine) { var assert = require('assert'); var swig = require('swig'); templateEngine = function(args) { assert.ok(args.engine, 'engine is required'); var templateEngine = {}; templateEngine.engine = args.engine; templateEngine.Render = function (templateString, model) { var result = swig.render(templateString, model); return result; }; return templateEngine; }; })(module.exports); 

Is there a way to use the above self-signed format and my module exports the constructor?

+6
source share
1 answer

In your second example, you just overwrite the templateEngine parameter and this will not have any effect.

To get the same result as your first example, simply:

Pass module into your IIFE:

 (function(module) { })(module); 

Assign the following to the property:

 (function(module) { var assert = require('assert'); var swig = require('swig'); module.exports = function (args) { ... }; })(module); 
+8
source

Source: https://habr.com/ru/post/982461/


All Articles