简体   繁体   中英

How to properly import/export a method in node js

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

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
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM