2016-07-25 40 views
-2

我正在使用節點js。我的app.js文件日益增長。我怎樣才能減少它。這樣我可以在其他文件中編寫代碼。儘管如此,我還是沒有試過,只是在谷歌上閱讀模塊。如何保持app.js文件很小

+0

你是怎麼去這個嗎? – alexi2

回答

0

您可以將代碼分成不同的文件,然後使用require將它們導入到app.js

var init = require('./config/init')(), 
config = require('./config/config') 

在上面的代碼中,我已經分居了一些​​初始化函數和配置文件到一個單獨的文件,我進口它。

0

一個簡單的例子可能是像下面,在你的app.js文件中設置您的服務器:

const express = require('express'); 
const http = require('http'); 
const app = express(); 

const router = require('./router'); // <= get your router here 


// Call the router, now you are listening 
// using the routes you have set up in the other file 
router(app); 

const server = http.createServer(app); 

server.listen(port,() => { 
    console.log('Server listening on port: ', port); 
}); 

而在你的路由器您在使用module.exports

module.exports = app => { 
    app.get('/', function(req, res) { 
    res.end('hello'); 
    } 
    // all your routes here 
} 
導出應用功能

現在你分離出了路由的邏輯。

您也可以使用相同的過程導出多個方法或變量。

myFuncs.js

func1 function() {} 
func2 function() {} 

module.exports = { 
    func1 
    func2 
} 

(注意這裏我使用ES6是一樣module.exports = { func1: func1, func2: func2 }

,然後要求他們以同樣的方式

const myFuncs = require('./myFuncs') 

myFuncs.func1() // <= call func1 
myFuncs.func2() // <= call func2 

你可以做與變量相同的操作,甚至可以與module.exports結合,以縮短您的代碼

個mySecrets.js

module.exports = {secret_key: 'verysecretkey'} 

app.js

const secret = require('./mySecrets') 

這樣,你可以讓你的api_keys等。在一個單獨的文件,或者你想爲需要導入甚至只是變量。

有提供更多的細節在這裏:https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

0

一個外部文件,例如內寫模塊:./hello.js

module.exports = { 
    function1 : function(){console.log('hello module');} 
}; 

加載中模塊的app.js

var hello = require('./hello.js'); 

// call your function 
hello.function1();