Split ES6 Class in multiple files to import individual methods of a library

Viewed 159

Let's say I build a library class for helper methods. I have one file containing string utils, one file containing ajax utils and so on.

The main class looks something like this:

// helperUtils.js
export class helperUtils {
  constructor() {}

  basicHelperFn() {
    return true;
  }
}

now i have a file exporting those string utils:

// helperUtils/stringUtils.js
import { helperUtils } from '../helperUtils.js';

helperUtils.prototype = { 
  stringUtil1 : (str) => { 
    return str += ' this is very helpful!';
  }
}

export const stringUtils = helperUtils.prototype;
// more files...
// helperUtils/ajaxUtils.js
// helperUtils/objUtils.js
// ...

How can I now import the main class and extend it with only some of the prototype methods splitted up over several files, for example only import the string utils.

import { helperUtils } from './helperUtils';
import { stringUtils} from './helperUtils/stringUtils';

const helper = new helperUtils();
helper.basicHelperFn();
helper.stringUtil1();
3 Answers

If your stringUtils class extends the helperUtils class:

// helperUtils/stringUtils.js
import { helperUtils } from '../helperUtils.js';

class StringUtils extends helperUtils {
    stringUtil1(str) {
         return str += ' this is very helpful!';
    }
}

export StringUtils;

then you can simply import it and use it.

Something like this ?

/*
 helperUtils/stringUtils.js 
*/
import { helperUtils } from '../helperUtils.js';

class StringUtils extends helperUtils {
    super();
    constructor() {}
    stringUtilNew(x) {
         /*
          Do somthing...
          */
         return x;
    }
}

export StringUtils;

I have experimented a bit more:

This i what I`ve been come up now:

// helperUtils/stringUtils.js
import { helperUtils } from '../helperUtils.js';

helperUtils.prototype.stringUtil1 = (str) => { 
    return str += ' this is very helpful!';
}

export const stringUtils = helperUtils.prototype;

Now the stringUtils prototype won't override my helperUtils prototype and I can safely import single methods to my main class.

If anyone got a better solution please share it with us!

Thanks so far!

Related