Can global constants be declared in JavaScript?

前端 未结 8 836
耶瑟儿~
耶瑟儿~ 2020-12-16 09:33

If so, what is the syntax for such a declaration?

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 09:56

    If you only care about supporting newer browsers (or are using a transpiler such as Babel to support older browsers) you can do the following:

    1. Create a settings.js file with whatever constants you want and export them:
    export const FRUIT = "kiwi";
    export const VEGETABLE = "carrot";
    
    1. In files that you want to use them you could then import them as follows:
    import * as Settings from './settings.js'
    
    1. Then to use the constants do something like this:
    console.log("The unchangeable fruit is " + Settings.FRUIT);
    

    This is a much cleaner approach than trying to implement a global constant, especially when you have multiple JavaScript files that you want to use the constants in.

提交回复
热议问题