Home Ask Login Register

Developers Planet

Your answer is one click away!

Ben February 2016

root directory for node module

I have a pretty standard node module using babel to transpile our code which is then output to a 'lib' folder. the package.json points 'main' to 'lib/index.js' so that people can just require('my-module')

However, if I have a subdirectory (say my-module/server for example) then when they use my-module they have to do require('my-module/lib/server'). I've seen people put post build steps that will copy package.json into lib, but that just feels hacky and wrong to me. Is there any way in npm to specify a main directory whereby any require()'s of my module would start at that directory? Then I can just have users do require('my-module/server') without the lib part...


Jose Santacruz Lopez February 2016

I think the best solution is that you have as main an index.js and on it all the submodules so you can do did something like require('your-module').server

ruffrey February 2016

It's hard without seeing your folder structure, but you can:

  • use module.exports = to export the babel output
  • symlink the other files into the directory


{ "main": "lib" }


module.exports = require('./path-to-transpiled-code.js');

// Now also export all the other stuff in this folder dynamically

fs.readdirSync(DIRECTORY_TO_EXPORT, function (err, files) {
  if (err) { throw err; }
  files.forEach(function (file) {
    if (file !== 'index.js') {
      fs.symlinkSync(path.join(__dirname, file), path.join(DIRECTORY_TO_EXPORT, file));

Post Status

Asked in February 2016
Viewed 1,765 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life