Home > front end >  How to properly import/export a method in node js
How to properly import/export a method in node js

Time:07-26

I am currently trying to import a method from a class to keep everything tidy since the method I plan to import will be quite long. However, I seem to get a new error every time I switch it up. The biggest issue is the import/export and the "event" parameter that don't seem to want to work with me.

Edit: The code works if I simply combine both classes and put the method in ImportingClass.js, however it would be too much code.

ValidateInput.js:

class ValidateInput
{
    validateInput(event)
    {
        var ID = event.target.StudentID.value;
        // ...
    }
}

ImportingClass.js:

import {validateInput} from '../ValidateInput';

class ImportingClass
{

    handleSubmit(event)
    {
        validateInput(this.event);
        // ...
    }
}

Error: Uncaught TypeError: (.validateInput) is not a function

CodePudding user response:

But we can do something like this as well

create an independent function validateInput

export function validateInput(e){
 .... code
}

and in order to call this function in your first class that is ValidateInput.js we can do something like this

class ValidateInput{
  validateInput(){
    validateInput.apply(this, ...args)
}}

and in your second file ImportingClass.js you can import and use it with import {validateInput} from './validateInput'

or you can export it via Prototype something like this

export const validateInput = ValidateInput.prototype.validateInput

CodePudding user response:

  1. You'll need to export the class so it can be called externally in a different module. The way to do this is by adding your class to the exports object.

ValidateInput.js:

class ValidateInput
{
    validateInput(event)
    {
        var ID = event.target.StudentID.value;
        // ...
    }
}

exports.ValidateInput = ValidateInput;
  1. Import your ValidateInput class in the module you would like to use it in.

ImportingClass.js:

// import {validateInput} from '../ValidateInput';
const fileName = require(../ValidateInput.js);

class ImportingClass
{

    handleSubmit(event)
    {
        fileName.ValidateInput.validateInput(this.event);
        // ...
    }
}

I've used the namespace fileName to avoid confusion. It refers to the file. The first property accessed is your class name, then the method you want to call. It can be a bit confusing if you are using virtually the same name for the file, class and method name.

  • Related