5

Is it possible to share constants between react and node - I am running node and react concurrently? For example, I have some constants I've defined on the client side using export const that could be useful to have on the server side, but node gives me an error when I try to const {x} = require('./constants'); because it can't import correctly. Has anyone run into this problem and found a solution?

React Constants:

// constants.js
export const X = 'x';
export const Y = 'y';
export const Z = 'z';

// App.js
import {x, y, z} from './constants';

Node Constants:

// constants_node.js
module.exports.username = 'foo_user';
module.exports.id = 10;

// server.js
const {username, id} = require('./constants_node');

3 Answers 3

0

If you are using the same node environment to serve your ReactJS components you can probably use environment variables for this purpose.

You can use a .env file and import it as process.env.VARIABLE_NAME where you want to use it.

Maybe this question - Pass or use process.env variable from node to reactjs can answer your question.

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. I would love to be able to understand what's going on with my problem as well and not have to rework much of my project. Great to know when starting a new project though.
0

In the latest version of react and node.js it is possible by using module.exports,

react version = "^18.2.0", and express version = "^4.18.2",

Defining

constants.js ( directory in the frontend, here react )

const var_1 = "variable_1";
const var_2 = "variable_2";

module.exports = {var_1, var_2 };

Accessing

  • Component.js (frontend, here react)

    import { var_1, var_2 } from "./constants"
    
  • Model.js (backend, here nodejs)

    import { var_1, var_2 } = require ("../../app/src/constants")
    

Comments

-1

My project is setup as follows:

Node is in project/ dir.

React is in project/src/ dir.

To share consts across both apps, I define them in project/src/consts/Consts.js and can be imported into either app like so:

import Consts from '../src/consts/Consts.js' // node
import Consts from '../consts/Consts.js' // react

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.