在 Node.js 中,我如何“包含"?我的其他文件中的功能?

2022-01-11 00:00:00 import node.js header javascript

假设我有一个名为 app.js 的文件.很简单:

Let's say I have a file called app.js. Pretty simple:

var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
  res.render('index', {locals: {
    title: 'NowJS + Express Example'
  }});
});

app.listen(8080);

如果我在tools.js"中有一个函数怎么办.我将如何导入它们以在 apps.js 中使用?

What if I have a functions inside "tools.js". How would I import them to use in apps.js?

或者...我应该把工具"变成一个模块,然后需要它吗?<<看起来很难,我宁愿做 tools.js 文件的基本导入.

Or...am I supposed to turn "tools" into a module, and then require it? << seems hard, I rather do the basic import of the tools.js file.

推荐答案

你可以 require 任何 js 文件,你只需要声明你想要暴露的内容.

You can require any js file, you just need to declare what you want to expose.

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}

在你的应用文件中:

// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined

相关文章