简体   繁体   English

如何将对象从单独的文件导出到Node和Javascript?

[英]How to export an object from a separate file to both Node and Javascript?

I have a file called utils.js which has some constants and I'm building a socket app which uses Node for backend work and regular Javascript for frontend. 我有一个名为utils.js的文件,该文件具有一些常量,并且正在构建一个套接字应用程序,该应用程序使用Node进行后端工作,并使用常规Javascript进行前端工作。 The names of the socket events are identical in both frontend and backend so I want to use the constants both in backend and frontend. 套接字事件的名称在前端和后端都是相同的,因此我想在后端和前端都使用常量。 But the syntax for exporting/importing is different in ecmascript6 as opposed to Node so how do I pull this off? 但是,与Node相比,ecmascript6中导出/导入的语法有所不同,那么如何实现呢?

This is the contents of utils.js : 这是utils.js的内容:

const EVENTS = {
    CONNECTION: 'connection',
    MESSAGE: 'message'
};
Object.freeze(EVENTS);
module.exports = EVENTS;

You can put the objects in JSON file, like events.json , or even event.js is you want plain JS objects. 您可以将对象放在JSON文件中,例如events.json ,甚至event.js都可以用作普通的JS对象。 Both the Node and JS have access to this. Node和JS都可以访问它。 Then you require/import this file in utils.js and you can do the same on the front end. 然后,您需要/在utils.js中导入此文件,并且可以在前端执行相同的操作。 Front and back ends can handle these however they want. 前端和后端可以根据需要处理这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM