Wednesday 21 December 2016

What do you think about require() taking a second, optional parameter: base path?

At some point you'll probably make a big enough Node app that you have to deal ../../with/this/path/problem to reach modules you want.There are a bunch of ways to mitigate this, but I feel that each has a drawback. For example, using a global var inline, you might do this;var Article = require(__base + 'app/models/article'); Which is fine, but it's both somewhat ugly and annoying to type. Also, it invites those little errors (e.g., did you remember to put the trailing / in your global path string?)The next would be with a module that expands the search path, but then you run into the issue of needing to know what is in your local path and what isn't. And it's a little unfriendly for other people who don't understand the structure of your code. You might accidentally include something you didn't expect because you didn't know the same name was in the local dir.I'm thinking it would be more elegant to add a second parameter to require that could be combined with a base path to explicitly show where you are looking for your module. And you could still use a global, so it might end up like this;require('app/thing/foo', __base); Using multiple globals, it also allows your app to be restructured (e.g., move base dirs around) by changing the path variable. So moving /models to /app/models would only require you to go update global.__models.require('user-model', __models); Anyone have any thoughts on that? I always like to vet out these ideas with others before bugging the dev channels with random requests.

Submitted December 21, 2016 at 04:43PM by khoker

No comments:

Post a Comment