是否可以在 react 和 Node 之间共享常量——我正在运行 Node 并同时 react ?例如,我有一些我在客户端使用 export const
定义的常量,这些常量在服务器端可能很有用,但是当我尝试 const 时 Node 给我一个错误{x} = require('./constants');
因为无法正确导入。有没有人遇到过这个问题并找到了解决方案?
react 常量:
// constants.js
export const X = 'x';
export const Y = 'y';
export const Z = 'z';
// App.js
import {x, y, z} from './constants';
Node 常量:
// constants_node.js
module.exports.username = 'foo_user';
module.exports.id = 10;
// server.js
const {username, id} = require('./constants_node');
最佳答案
如果您使用相同的 Node 环境来为您的 ReactJS 组件提供服务,您可能可以为此目的使用环境变量。
您可以使用 .env
文件并将其作为 process.env.VARIABLE_NAME
导入到您要使用的位置。
也许这个问题 - Pass or use process.env variable from node to reactjs可以回答你的问题。
关于node.js - 在 Node 和 React 之间共享常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49546041/