Noitidart
Noitidart

Reputation: 37328

Inline import the default export into array

I have multiple files called PageX, PageY, PageZ etc.

Each of these have an export default SETUP { path:'blah_X', component:X }.

In my index.js I want to import these SETUPs into an array like this:

const PAGE_SETUPS = [
   import './PageX',
   import './PageY',
   import './PageZ' 
];

const routes = PAGE_SETUPS.map(setup => createElement(Route, {path:setup.path, component:setup.component});

I am hitting all kinds of issues. Is this possible to inline-import the default exported item into an array like this?

Upvotes: 5

Views: 5492

Answers (2)

James
James

Reputation: 73

What I would do is have this be in a pages directory with an index.mjs file alongside all your pages. Then you can import all your pages and export the array. From that index file you could export an array of your pages and import that in another module.

// pages/index.js
import PageX from './PageX',
import PageY from './PageY',
import PageZ from './PageZ' 
export const PAGE_SETUPS = [PageX, PageY, PageZ];

Then you would just need to import your array in another file.

//some other module
import PAGE_SETUPS from './pages/index.mjs'
const routes = PAGE_SETUPS

Alternatively you could pass your modules through the original page/index.js file instead of exporting an array.

// pages/index.js
export * from './PageX',
export * from './PageY',
export * from './PageZ' 
// some other module
import {PageX, PageY, PageZ} from './pages/index.mjs'

const routes = [
  PageX,
  PageY, 
  PageZ
]

Upvotes: 1

Bergi
Bergi

Reputation: 665536

No, there are no "inline imports" in ES6 modules. You can either use whichever kind of non-declarative import method the module loading system that you transpile to offers, or you have to spell it out:

import PageX from './PageX',
import PageY from './PageY',
import PageZ from './PageZ' 
const PAGE_SETUPS = [PageX, PageY, PageZ];

Upvotes: 11

Related Questions