我可以在文件中定义公共依赖项,然后在 commonJS 中导入它吗?

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

我有几个构建任务需要相同的依赖项。使两个依赖项列表保持最新是一件很麻烦的事情,所以我想知道:有没有一种方法可以定义共享的依赖项,然后为两个构建任务导入它们?

假设我需要两个文件的 glob 模块。我能做吗:

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

module.exports = something

然后在两个文件中导入 shared.js 以获得这些依赖项?

我会将我的回答分为两部分:技术和个人意见。

技术

你可以很容易地做到这一点。

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

个人意见

我认为这不是一个好主意,因为 require () 语法并不那么冗长而且绝对不复杂。缺点是您可能会发现共享模块的使用方式确实比每个模块真正需要的导入更多。它还对可读性产生负面影响,因为 shared.a 的可读性明显低于 var a = require('specific-path/a')