LoginSignup
2
4

More than 5 years have passed since last update.

node.js で express を使っている際の require のパスの書き方メモ

Posted at

読み込むファイルからの相対パスで繋ぐと、 ../ が沢山になるので、
グローバル変数にアプリのROOTパスを入れて、各ファイルではROOTパスを使った絶対パスを使う。

app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');

// ----------------------------------------
// 変数の設定
global.app_root = __dirname;
// ----------------------------------------

var index = require('./routes/index');

var app = express();

// view engine setup
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.set('view cache', false);
swig.setDefaults({ cache: false });

...
各ファイル
var StringUtil = require(global.app_root + "/common/util/string_util.js");

注意として app.js の最初の方で宣言しないと、各ファイルの読み込み時に間に合わない可能性があるので、
なるだけ頭の方で宣言する。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4