Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Only Static Variable from ES6 module

I have a file common.js which contains the common variables and methods used on my App, such as a nav-bar module (nav-bar.js), and some others.

Generally, every module on my app will need to import the whole common.js module, except from login module. This one just need one of the contants defined on common.js.

If I used named imports to do something like:

$ import {RestURL} from "./common";

I realize that, yes, I can use RestURL const inside my login module, but all modules imported in common.js are imported as well, including the nav-bar module, which execute code that I do not want to be executed.

I wonder... Is there anyway to import ONLY the corresponding variable, RestURL, like a static variable, without running all the common.js code, that is, without importing all modules imported inside common.js file such as nav-bar.js module?

Thank you!!!

// -- common.js ---------------------------------------------------
import '../inc/nav-bar';        // NAV-BAR JS

export const RestURL = {
    login:          '/services/b2b/v2/login',
}
// -- end of common.js module -------------------------------------



// -- login.js ----------------------------------------------------
import {RestURL} from "./common";

console.log(RestURL.login);
// -- end of login.js module --------------------------------------

I need to use RestURL const inside login.js module, but I do not want nav-bar.js to be imported, since there is code inside it that I do not need to be exectuted when loading login.js. With the named import approach I manage to access the const RestURL, but the nav-bar module is loaded as well... :(

like image 483
ÁngelBlanco Avatar asked Apr 12 '26 15:04

ÁngelBlanco


1 Answers

You could break the modules into two and import in both the modules.

// -- const.js ---------------------------------------------------

export const RestURL = {
    login:          '/services/b2b/v2/login',
}
// -- end of const.js module -------------------------------------


// -- common.js ---------------------------------------------------
import '../inc/nav-bar';        // NAV-BAR JS
import {RestURL} from './const.js'

// -- end of common.js module -------------------------------------




// -- login.js ----------------------------------------------------
import {RestURL} from './const.js'

console.log(RestURL.login);
// -- end of login.js module ----
like image 123
StateLess Avatar answered Apr 15 '26 06:04

StateLess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!