React create constants file

后端 未结 4 1164
盖世英雄少女心
盖世英雄少女心 2021-01-31 07:08

How to create constants file like: key - value in ReactJs,

ACTION_INVALID = \"This action is invalid!\"

and to use that in other components

相关标签:
4条回答
  • 2021-01-31 07:45

    You can simply create an object for your constants:

    const myConstClass = {
        ACTION_INVALID: "This action is invalid!"
    }
    

    And then use it.

    If you are bundling, you can export this object and then import for each component file.

    0 讨论(0)
  • 2021-01-31 07:49

    One way to do that (not so different from other answers though) is to create a bare constants.js file and add your constants there.

    module.exports = Object.freeze({
      ACTION_INVALID: 'This action is invalid',
      ACTION_VALID: 'Some other action',
    });
    

    Then you can import it

    import ConstantsList from './constants';
    

    and use

    console.log(ConstantsList.ACTION_INVALID)
    

    As the name suggests, Object.freeze() freezes objects and stops anyone from changing the values. Please note: if the values are objects themselves they are changeable (unless they are also frozen)

    0 讨论(0)
  • 2021-01-31 08:04

    Expanding on Monad's answer, for situations where you don't want to type myConstClass all the time:

    fileWithConstants.js:

    export const ACTION_INVALID = "This action is invalid!"
    export const CONSTANT_NUMBER_1 = 'hello I am a constant';
    export const CONSTANT_NUMBER_2 = 'hello I am also a constant';
    

    fileThatUsesConstants.js:

    import { ACTION_INVALID } from 'path/to/fileWithConstants';
    
    const errorMsg = ACTION_INVALID;
    

    (Also, if Monad's way works better for you, I believe the convention is for 'MyConstClass' to start with a capital letter, since it's acting like a class in code.)

    0 讨论(0)
  • 2021-01-31 08:06

    I'm not entirely sure I got your question but if I did it should be quite simple:

    From my understanding you just want to create a file with constants and use it in another file.

    fileWithConstants.js:

    export const ACTION_INVALID = "This action is invalid!"
    export const CONSTANT_NUMBER_1 = 'hello I am a constant';
    export const CONSTANT_NUMBER_2 = 'hello I am also a constant';
    

    fileThatUsesConstants.js:

    import * as myConstClass from 'path/to/fileWithConstants';
    
    const errorMsg = myConstClass.ACTION_INVALID;
    

    If you are using react you should have either webpack or packager (for react-native) so you should have babel which can translate your use of export and import to older js.

    0 讨论(0)
提交回复
热议问题