Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 - import all named module without alias

I know that we can import all named modules with alias as below,

import * as name from "module-name"; 

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Actually, I have re-exported my modules in A.js and the same is inherited in B.js. PFB. Now, it's two level of inheritance, so it's not a big deal to import the named modules. But, when I'm taking this to 5 level of inheritance (A -> B -> C -> D -> E), I need to import all named modules in all files and need to do the (re)export the same in all. Instead of doing this,

  • Is there any other way to copy scope of all named modules into all level without reiterating the wheel (Import and Export)
  • Behind the scene of this design is to make them to follow Opps concept and to avoid the redeclaration of the same modules.

A.js

import React from 'react'; import I18n from 'i18n-js'; import m1 from 'module1'; import m2 from 'module2';  export default class A extends React.Component {}  export {React, I18n, m1, m2) 

B.js

import BaseComponent from './A'; import {React, I18n, m1, m2) from './A;  export default class B extends A {} 

Is there any way to import all named modules without alias like import {*} from './A' (instead of 2nd in B.js)

like image 638
Mr. Black Avatar asked Jan 03 '16 05:01

Mr. Black


2 Answers

Is there any way to import all named modules without alias like import {*} from './A' (instead of 2nd in B.js)

No.

And the whole idea of re-exporting more than you need to save the "number of lines" in the final js file as you stated at

Because, It's putting two lines for each import in the final js file. Consider If there are 10 import lines than, 20 lines will be added in final js. When you are thinking for production it will too cost

Does not make much sense, since that's what JS minifiers are for.

To summarise: one should not do that at the very first place:

  1. You export only what you need to export
  2. You import whatever you need wherever you need.
  3. You use JS minifiers to optimise the output JS file size.
like image 53
zerkms Avatar answered Sep 22 '22 02:09

zerkms


JavaScript solution:

import * as exports from 'foo'; Object.entries(exports).forEach(([name, exported]) => window[name] = exported); 

Note: the imported wrapper object remains there.


Node.js solution:

Object.entries(require('foo')).forEach(([name, exported]) => global[name] = exported); 
like image 25
Csaba Fityó Avatar answered Sep 24 '22 02:09

Csaba Fityó