本文介紹了在 Node.js 中,我如何“包含"?我的其他文件中的功能?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
假設(shè)我有一個名為 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"中有一個函數(shù)怎么辦.我將如何導(dǎo)入它們以在 apps.js 中使用?
What if I have a functions inside "tools.js". How would I import them to use in apps.js?
或者...我應(yīng)該把工具"變成一個模塊,然后需要它嗎?<<看起來很難,我寧愿做 tools.js 文件的基本導(dǎo)入.
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 文件,你只需要聲明你想要暴露的內(nèi)容.
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 () {
}
在你的應(yīng)用文件中:
// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined
這篇關(guān)于在 Node.js 中,我如何“包含"?我的其他文件中的功能?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!