2016-07-25 3 views
-2

私はノードjsで作業しています。毎日私のapp.jsファイルが長くなっています。どうすれば減らすことができますか?私は他のファイルにコードを書くことができるように。まだ私は何も試していないが、googleのモジュールについて読む。app.jsファイルを小さく保つ方法

+0

これと一緒に行く? – alexi2

答えて

0

あなたは別のファイルにコードを分離し、その後、私は別のファイルにいくつかのinit関数と設定ファイルを分離していると私は輸入しています上記のコードでapp.js

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

にインポートするrequireを使用することができますそれ。

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 
} 

(私はそれがmodule.exports = { func1: func1, func2: func2 }

と同じであるES6を使用して、あなたが行うことができます同じように

const myFuncs = require('./myFuncs') 

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

を、それらを必要としていますここで注意変数を使用して同じ操作を実行し、module.exportsと組み合わせてコードを短縮しても

mySecrets.jsあなたが別のファイル、またはあなたが必要に応じてインポートするだけでも、変数に...など、あなたのapi_keysを保つことができる方法

module.exports = {secret_key: 'verysecretkey'} 

app.js

const secret = require('./mySecrets') 

詳細は、こちらをご覧あります./hello.jshttps://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

0

は、外部ファイルなどの内部モジュールを書く

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

あなたapp.js内にロードするモジュール:

あなたはどうやっ
var hello = require('./hello.js'); 

// call your function 
hello.function1(); 
関連する問題