Can I define common dependencies in a file, and import that in commonJS?

I've got several build tasks that require the same dependencies. It is quite a chore to keep both dependency lists up to date, so I was wondering: is there a way to define dependencies that are shared and then import them for both build tasks?

Say I require the glob module for both files. Can I do:

// shared.js
var glob = require('glob');

module.exports = something

And then import shared.js in both files to get those dependencies?

Upvotes: 0

Views: 291

Answers (1)

Amit
Amit

Reputation: 46323

I'll split my answer to 2 parts: Technical & Personal opinion.

Technical

You can do that quite easily.

shared.js

module.exports = {
  a: require('a'),
  b: require('b')
  // and as long as required...
}

build.js

var shared = require('shared')
// and if you'd like...
var a = shared.a
var b = shared.b

Personal opinion

I don't think it's a good idea as the require () syntax is not that verbose and definitely not complicated. The downside will be that you'll likely find that your shared module is utilized in a way that does import more than each and every module really needs. Also it has a negative impact on readability, since seeing shared.a is significantly less readable than var a = require('specific-path/a')

Upvotes: 1

Related Questions