skip to Main Content

I want export many variables something like this

const ENUMS = {
    ACCOUNTNAME_LENGTH      : 52,
    ACCOUNTPASS_LENGTH      : 36,
    SZNAME_LENGTH           : 20,
    // ... and 1000 more variables 
}

export { ... ENUMS } // ERROR

I want to access each variable directly by its name from other script

var value = ACCOUNTNAME_LENGTH

… without have to use ENUMS object eg:

var value = ENUMS.ACCOUNTNAME_LENGTH

how can I accomplish that, thanks

Syntax Error using Node.JS

2

Answers


  1. // consts.js
    export const ACCOUNTNAME_LENGTH = 32
    export const ACCOUNTPASS_LENGTH = 42
    ...
    
    
    // app.js
    import {ACCOUNTNAME_LENGTH, ACCOUNTPASS_LENGTH} from "./consts.js"
    

    just repeat for your 1000 variables… or bite the bullet and use a namespace import.

    Login or Signup to reply.
  2. I assume you want to expose all the properties as variables without specifically importing them.

    First, I want to clarify that this is generally not a good idea, clutters up the scope and might lead to variables inadvertently overriding each other if the other module contains similarly named variables.

    Second, this solution uses the with statement, which is deprecated and generally not considered a good practice (see the note on MDN)

    Having said that:

    // enums.js
    export const ENUMS = {
        ACCOUNTNAME_LENGTH      : 52,
        ACCOUNTPASS_LENGTH      : 36,
        SZNAME_LENGTH           : 20,
        // ... and 1000 more variables 
    }
    
    // then in the other module
    import { ENUMS } from './enums.js';
    
    with (ENUMS) {
      // you can use ENUMS properties here as variables
      // not a good idea!
      console.log(ACCOUNTNAME_LENGTH)  // 52
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search