DEV Community

Aad Pouw
Aad Pouw

Posted on

What I just learned about 'import * as NAMESPACE'

Backstory:

I was looking for a way to get the creating of menus and related templates automated instead of doing that manually.
All I knew was that I had to create an array of my template files for processing in my framework.
Just as I had no idea of where to begin or how to get that done.
I began with observing of my 'site_data.js (this file is outside of domFramework!)'.
Here my eyes fell on the import rules that I have on top and most of them are like this 'import * as TE from './path/to/templates_export.js''.

"My habit in here is to create an *uppercased abbreviation* out of the file name and use that as a *namespace*."

Fastforward:

Here I picked up the idea to pass that namespace in a console.log to see what would happen and this is what I got
Object { tpl_00: async tpl_00(obj_args), tpl_01: async tpl_01(obj_args), … }
That was a discovery, because I never had a look at it before.
Now I had something to work on! I had to find a way to create an array out of it.

➜ Step one:

 const tpl = [];
 tpl.push(TE);
 console.table({'tpl':tpl});

  ☛ (index) 0[{tpl_00: async tpl_00(obj_args), tpl_01: async tpl_01(obj_args), … }]
  ☛ Nice, here I have an array now but not very useful!

➜ Step two:

 const tpl_raw = [];
 tpl_raw.push(TE);
 const tpl = Object.values(tpl_raw[0]);
 console.table({'tpl':tpl});

  ☛ (index) [async function tpl_00(obj_args),async function tpl_01(obj_args),...]
  ☛ Where I was after an array that grows anytime when I add a file to 'templates_export.js (TE)' 😇!

➜ Finally I created a function out of it:

 export async function getNamespaceItems(...args){
   const [ns = null] = args;
   if(ns !== null){
     const items_raw = [];
     items_raw.push(ns);
     return await Object.values(items_raw[0]);
   }
   return;
 }

  ☛ This function returns a nice self growing array out of just a namespace 😄!

➜ How to use?

 const tpl_items = await MH.getNamespaceItems(TE);
 for(const tpl_item of tpl_items){
   const tpl = await tpl_item(sd_data);
   //other code!                    
}

  ☛ Results:

  tpl <content-item class="relative display-flex" data-a-link="/dfwdemo/" data-tpl-layer="def" data-prefix="default" data-is-default data-nav-title="Home"></content-item>
  tpl < content-item class="relative display-flex" data-a-link="#topic_one" data-nav-title="Topic 1" data-prefix="one" data-tpl-layer="one"></content-item>           
  //more ...

  ☛ This way and by making use of  'data attributes'  I'm able to add menu-items/templates by just creating a template file and adding it to the export.js 😄!
  ☛ Yes, this is just a 🍰 of the pie and there is much more involved but that is out of this topic!

➜ When to use and not to use?
  ☛ When an array is needed from simular objects, like my templates.
  ☛ When not to use? That's simple anything other as that.

Top comments (0)