0

I'm new with NodeJs, my project is growing and i dont want make relative imports, i want imports like these installed from npm.

I have the following directory structure

Project node_modules/ src/ model/ person.js test/ model/ person.js app.js config.js

i'm using mongoose and i can require mongoose from any place with require('mongoose') but by example if a want require my person model from app.js i write require('./model/person') and from my test/model/person.js i need write require('../../src/model/person').

Exist some way "native" (without install more dependencies) to make this some like require('model/person') from any place of my app?

rkmax
  • 17,633
  • 23
  • 91
  • 176

2 Answers2

2

This topic is extensively discussed here. My conclusion is mostly:

  1. The idea of putting tests in a separate directory is ineffective. Put tests right alongside the main code: app/users/user.js and app/users/user.test.js.
  2. I create a symlink at node_modules/app that points to ../app so I can require('app/users'); from anywhere in the code base.
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • the symlink does the trick, but can you explain why putting tests in a separate directory is ineffective? – rkmax Dec 10 '14 at 05:33
  • Because of this issue. In general, after having tried the other approaches, I want modular software where all the tightly coupled stuff lives together in the filesystem and loosely coupled stuff lives far apart. Tests are tightly coupled to the code under test, so keep them together. – Peter Lyons Dec 10 '14 at 06:11
  • Somehow I accidentally down-voted this. Unfortunately it's been over 12 hours, so I cannot undo it. If you make an edit to the answer I'll fix it! – Timothy Strimple Dec 10 '14 at 18:08
0

There is nothing which says you cannot put your own code inside node_modules. This will enable you to reference it as you want. If you have a .gitignore or equivalent preventing code inside node_modules from being committed, you can add exceptions for your own code.

node_modules
!node_modules/model/
Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76