How to properly require files into another file

◇◆丶佛笑我妖孽 提交于 2019-12-25 00:50:28

问题


I have a bunch of js script files that use require to require the same series of libraries, etc.'

let path = require('path');
let _ = require('underscore');

I want to put all these requirements into a separate library file that I can then reuse amongst the files that need them. I though I could do something like this:

var common = function() {
    this.requireFiles = function() {
        let path = require('path');
        let _ = require('underscore');
        ...
    }
};
export.common = common;

However, when I want to include this library in those files that use all these same files, it does not work. I am trying something like this:

let CommonTools = require('../server_libs/commonFiles').common;
let commonFiles = new CommonTools();
migration.requireFiles();

This give me an error that _ is not a function, when I want to use the underscore methods. Any hints as to where I should look for better understanding on this topic?


回答1:


I personally do not recommend making a common module. The node.js module mentality is to just require() in what a module needs. Yes, it seems like a little extra/redundant typing in each module, but it makes each module self describing and does not build any unnecessary dependencies between modules leading to the simplest module sharing or reuse options. Modules are cached by the require() sub-system so it doesn't really cost you at runtime to just require() in each module as you need them. This is pretty much the node.js way.

That said, if you really want to make a common module, you can do it like this:

common.js

module.exports = {
    _: require('underscore');
    path: require('path');
}

otherModule.js

const {_, path} = require('common.js');

// can now call underscore methods _.each()
// can now call path methods path.join()

This uses destructing assignment to get properties from the common.js exports and assign them to a module-scoped variable and to do it for multiple properties in one statement. It still requires you to list each property you want defined in this module (which helps self describe what you're doing).

This also assume you're using require() and module.exports. If you're using the newer import and export keywords, then you can modify the syntax accordingly, but still use the same concept.



来源:https://stackoverflow.com/questions/50281365/how-to-properly-require-files-into-another-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!