在 Node.js 中包含另一个文件中的 JavaScript 类定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6998355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Including JavaScript class definition from another file in Node.js
提问by martin
I'm writing a simple server for Node.js and I'm using my own class called User
which looks like:
我正在为 Node.js 编写一个简单的服务器,我正在使用我自己的类User
,它看起来像:
function User(socket) {
this.socket = socket;
this.nickname = null;
/* ... just the typical source code like functions, variables and bugs ... */
this.write = function(object) {
this.socket.write(JSON.stringify(object));
}
};
and then later in the process I'm instantiating it a lot:
然后在这个过程的后期我实例化了很多:
var server = net.createServer(function (socket) {
/* other bugs */
var user = new User(socket);
/* more bugs and bad practise */
});
Can I move my User
class definition to another javascript file and "include" it somehow?
我可以将我的User
类定义移动到另一个 javascript 文件并以某种方式“包含”它吗?
回答by Paul Rumkin
Option A
选项 A
You can simply do this:
你可以简单地这样做:
user.js
用户.js
class User {
//...
}
module.exports = User
server.js
服务器.js
const User = require('./user.js')
// Instantiate User:
let user = new User()
Option B
选项 B
Sometimes it's useful to export several classes or functions from a single file. Here is an example of this:
有时从单个文件导出多个类或函数很有用。这是一个例子:
user.js
用户.js
class User {}
exports.User = User
exports.foo = 0
exports.bar = 1
server.js
服务器.js
const {User, foo, bar} = require('./user.js')
// Instantiate User:
let user = new User()
ES Modules
ES 模块
Since ES Modules became a standard, some authors have started use them in articles and tutorials, what may be confusing, because Node.js has only experimental support of ESM and meantime Node.js version prior 13.0 requires a flag to make ESM work. Read about it in Node.js' v13 ESM documentation.
由于 ES Modules 成为标准,一些作者开始在文章和教程中使用它们,这可能令人困惑,因为 Node.js 仅对 ESM 提供实验性支持,而 Node.js 13.0 之前的版本需要一个标志才能使 ESM 工作。在 Node.js 的 v13 ESM 文档 中了解它。
Here it is an example of the same behavior implemented with ESM:
这是使用 ESM 实现的相同行为的示例:
user.js
用户.js
export default class User {}
server.js
服务器.js
import User from './user.js'
let user = new User()
Note
笔记
?? Don't use globals, it creates potential conflicts with the future code.
?? 不要使用全局变量,它会与未来的代码产生潜在的冲突。
回答by yedidyak
Using ES6, you can have user.js
:
使用 ES6,你可以user.js
:
export default class User {
constructor() {
...
}
}
And then use it in server.js
然后在 server.js
const User = require('./user.js').default;
const user = new User();
回答by sevenflow
Modify your class definition to read like this:
修改您的类定义,如下所示:
exports.User = function (socket) {
...
};
Then rename the file to user.js
. Assuming it's in the root directory of your main script, you can include it like this:
然后将文件重命名为user.js
. 假设它在你的主脚本的根目录中,你可以像这样包含它:
var user = require('./user');
var someUser = new user.User();
That's the quick and dirty version. Read about CommonJS Modulesif you'd like to learn more.
那是快速而肮脏的版本。如果您想了解更多信息,请阅读CommonJS 模块。
回答by Gaurav Rawat
Another way in addition to the ones provided here for ES6
除了此处为 ES6 提供的方法之外的另一种方法
module.exports = class TEST{
constructor(size) {
this.map = new MAp();
this.size = size;
}
get(key) {
return this.map.get(key);
}
length() {
return this.map.size;
}
}
and include the same as
并包括与
var TEST= require('./TEST');
var test = new TEST(1);
回答by pimvdb
If you append this to user.js
:
如果您将此附加到user.js
:
exports.User = User;
then in server.js
you can do:
然后server.js
你可以这样做:
var userFile = require('./user.js');
var User = userFile.User;
http://nodejs.org/docs/v0.4.10/api/globals.html#require
http://nodejs.org/docs/v0.4.10/api/globals.html#require
Another way is:
另一种方式是:
global.User = User;
then this would be enough in server.js
:
那么这就足够了server.js
:
require('./user.js');
回答by Ernesto
Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel
而不是 myFile.js 编写像 myFile.mjs 这样的文件。这个扩展带有 es6 的所有优点,但我的意思是我向你推荐 webpack 和 Babel
回答by Aft3rL1f3
I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.
我只想指出,这里的大多数答案都不起作用,如果“module.exports.yourClass”方法一直发生变化,或者人们刚刚输入了错误的答案,我是 NodeJS 和 IDK 的新手。
// MyClass
module.exports.Ninja = class Ninja{
test(){
console.log('TESTING 1... 2... 3...');
};
}
//Using MyClass in seprate File
const ninjaFw = require('./NinjaFw');
let ninja = new ninjaFw.Ninja();
ninja.test();
- This is the method I am currently using. I like this syntax, becuase module.exports sits on the same line as the class declaration and that cleans the code up a little imo. The other way you can do it is like this:
- 这是我目前使用的方法。我喜欢这种语法,因为 module.exports 与类声明位于同一行,这样可以稍微清理代码。另一种方法是这样的:
// Ninja Framework File
class Ninja{
test(){
console.log('TESTING 1... 2... 3...');
};
}
module.exports.Ninja = Ninja;
- Two different syntax but, in the end, the same result. Just a matter of syntax anesthetics.
- 两种不同的语法,但最终结果相同。只是语法麻醉剂的问题。