Skip to content

How to refer a variable in Node.js from another file

I am using node.js to build an app where I have a lot of static text (may change over months) in the code. I want to move the text in a separate file and refer that file data as a variable in the handler file.

E.g.

const result = await client.views.open({
            view: {
                type: 'new',
                text:  [{
                    text: {
                        type: "plain_text",
                        text: "One",
                        emoji: true
                    },
                    value: "One"
                },
                {
                    text: {
                        type: "plain_text",
                        text: "Two",
                        emoji: true
                    },
                    value: "Two"
                }
                ]
                }
            });
            } catch (error) {
                 console.error(error);
            }

The above is original file code. What I want to do is move the below code to a separate file:

                   [{
                        text: {
                            type: "plain_text",
                            text: "One",
                            emoji: true
                        },
                        value: "One"
                    },
                    {
                        text: {
                            type: "plain_text",
                            text: "Two",
                            emoji: true
                        },
                        value: "Two"
                    }
                    ]

And there after use something like require(./newfile.js) to refer to that as a variable in the handler file.

The issue I am facing is this is not a valid JSON, but an object with JSON structure so unsure how to work around this .

Answer

In newfile.js

module.exports = [
    {
        text: {
             type: "plain_text",
             text: "One",
             emoji: true
        },
        value: "One"
     },
     {
         text: {
              type: "plain_text",
              text: "Two",
              emoji: true
         },
         value: "Two"
     }
]

Then import it in your original file:

const innerText = require('./newfile.js');

const result = await client.views.open({
    view: {
        type: 'new',
        text: innerText,
    }
});