gpt4 book ai didi

node.js - 在 Node 和 React 之间共享常量变量

转载 作者:搜寻专家 更新时间:2023-11-01 00:04:20 24 4
gpt4 key购买 nike

是否可以在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com