souparno majumder
souparno majumder

Reputation: 2052

how to require a module without mentioning the relative file path

this is an example folder structure

folder1
--lib
----app.js

folder 2
--www
----Application.js

The Application.js file in the folder2 requires app.js file from the folder1 in the following way var app = require('../../folder1/lib/app') and then Application.js is browserified.

What I want to achive is require the app.js into the Application.js without mentioning the path .ie var app = require('app') and without changing the folder structure, but on being browseried it will map the actual file i.e. folder1/lib/app.js for require('app').

EDIT

I am thinking about creating a file in folder1 that will be responsible to browserify the code in folder2. Ex: $folder2> node ../folder1/build.js www/Application.js will output a browserified file mapping require('app') to the app.js in folder1

Upvotes: 1

Views: 120

Answers (1)

Louay Alakkad
Louay Alakkad

Reputation: 7408

I tend to use app-module-path for this.

My folder structure:

index.js
app/
   lib/
     hash.js
   controllers/
     index.js
   middleware/
     auth.js

and in index.js:

require('app-module-path').addPath(__dirname);

Then for example in controllers/index.js, I can just do this:

var auth = require('app/middleware/auth');
var hash = require('app/lib/hash');

This is for nodejs. Now for browserify you can use aliasify.

replacements: {
  "app/(\\w+)": "app/$1"
}

It makes things much cleaner. 👍

Upvotes: 1

Related Questions