Search code examples
javascriptjavascript-objectsjavascript-import

Importing / exporting Javascript Object Properties


I support a relatively complex legacy codebase, but am looking to modernise it a little by bringing in Webpack so that we'd have import & export capabilities in JS.

The problem I'm having is that we use a global object called App where we define and add different properties depending on the page. So for example we have the following file where we instantiate App (loaded on all pages):

app.js

const App = (() => {
    const obj = {
        Lib: {},
        Util: {},
        // etc
    }

    return obj;
})();

Then in another file we add to App.Lib just for the specific page that needs it:

lazyload.js

App.Lib.Lazyload = (() => {
    // lazyload logic
})();

We simply concatenate the files during the bundling process, but obviously this is not ideal as none of the files have no knowledge of what goes on outside of it.

Exporting only seems to work for the top level object (where the object is defined), so anything I add to it elsewhere cannot be exported again. For example if I add export default App.Lib.Lazyload; at the end of lazyload.js and then try to import it elsewhere it will not import the Lazyload property.

Is there any way to get this to work without major refactor? If not, would you have any suggestions about the best way to handle it?


Solution

  • I don't think you can import Object.properties in JS. If you want to bundle specific packages (say Lazyload) for packages that need them, you might try:

    //lazyload.js
    export const LazyLoad = {
      //lazyload logic
    }
    

    then somewhere else...

    import {LazyLoad} from 'path/to/lazyload.js';
    
    // assuming App has already been created/instantiated
    App.Lib.Lazyload = LazyLoad;
    

    Using Export Default...

    //lazyload.js
    const LazyLoad = {};
    export default LazyLoad;
    

    then...

    import LazyLoad from 'path/to/lazyload.js';
    App.Lib.LazyLoad = LazyLoad;
    

    You can find help with Imports and Exports at MDN.