Home > front end >  How to export/import constructor functions?
How to export/import constructor functions?

Time:10-31

With the following UMD export:

(function(factory) {

    module.exports = factory();

} (function() {


    function test() {
        this.param = 'This is a test';
    
        this.init = function() {
            console.log(this.param)
        }
    
        this.init();
    }

    return test;
    
}));

I tried to import the test function, and to initialize an instance

import {test} from 'path/to/test'


const myTest = new test();

Result:

test is not a constructor

CodePudding user response:

Either correct the import

import test from 'path/to/test'

or the export

return { test };

CodePudding user response:

Just use a global browser global export; don't export it inside the function. More information: Export module pattern.

Try the following .js code:

module.exports = (function (factory) {
  return factory();
}(function () {
  function test() {
    this.param = 'This is a test';
    this.init = function () {
      console.log(this.param)
    }
    this.init();
  }

  return test;
}));
  • Related