Search code examples
javascriptmodulecomponents

Import into an object? Best practices for organizing a module library


Hi 👋 I want to create a module library with a set of helper functions. Not sure where to put the code to keep everything organized, was first thinking to create it like:

lib-name
 - main.js
 - some-module
    - some-part-of-the-module.js
    - some-other-part-of-the-module.js

However when accessing the objects in the library, I would like to be able to use dot scoping, like

lib-name.some-module.some-thing("This is a function argument!");

both to avoid ODR violations & avoid having 10-50 lines worth of imports.

How would I best set this up? Was hoping for a completely vanilla solution, though if there are any common libraries for this sort of thing out there Im all ears. Im writing my project completely without frontend frameworks and using a flask backend (the latter of which I dont think is relevant?). Would ideally like to avoid having to use a build system at the very least.

Have been looking a bit already at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules, but it seems that import doesn't support importing into existing objects - making it difficult to achieve my . accessor dream without too much of a hassle.


Solution

  • this is just my idea and there might be a better way of doing this. continue from my comment, here what i would do:

    libname/
      some-module/
        some-part-of-the-module.js
        some-other-part-of-the-module.js
      index.js
    

    the index.js is the bridge file. inside it would be like:

    import { someFunction } from './some-module/some-part-of-the-module.js';
    import { someOtherFunction } from './some-module/some-other-part-of-the-module.js';
    
    const libname = {
      someFunction,
      someOtherFunction
    }
    
    export default libname;
    

    and when you want to use, you would do something like:

    import libname from "libname";
    
    libname.someFunction();
    libname.someOtherFunction();
    

    note: the bridge file's named index.js because when your import something from it, you don't need to specify the file name.