从各个模块中获取单独的导出

时间:2019-06-26 23:17:27

标签: javascript node.js

modules.js中,我有以下代码:

module.exports = {
    BookingHotel: function() {
        this.getId = function(id) {
            return "Hello World";
        },

        this.getAll = function() {
            return "Hello World";
        }
    },

    BookingFlight: function() {
        this.book = function() {
            return "Hello World";
        }
    },    
}

modules.js文件太大,难以维护。

如何将BookingHotelBookingFlight分成单独的文件,并像当前一样导出它们?

2 个答案:

答案 0 :(得分:1)

modules.js中的每次导出制作一个单独的JavaScript文件,并使每个文件导出一个功能,然后只需要每个文件并重新导出如下功能即可:

注意:单个文件的名称并不重要,只要它们与modules.js中使用的文件名一致即可。

BookingHotel.js:

module.exports = {
    BookingHotel: function() {
        // Your code here
    }
};

BookingFlight.js:

module.exports = {
    BookingFlight: function() {
        // Your code here
    }
};

modules.js:

// Get the exports from BookingHotel.js
var BookingHotelExports = require("./BookingHotel.js");
// Get the exports from BookingFlight.js
var BookingFlightExports = require("./BookingFlight.js");
// Combine the individual exports from the two required modules into a new exports variable for this module.
module.exports = {
    // BookingHotel is a property of the module.exports object from BookingHotel.js.
    BookingHotel: BookingHotelExports.BookingHotel,
    // Same here, but from BookingFlight.js.
    BookingFlight: BookingFlightExports.BookingFlight
};

答案 1 :(得分:1)

  1. 为对象创建单独的文件: BookingHotel.js BookingFlight.js

  2. 从相应文件中导出对象:

BookingHotel.js:

export default var BookingHotel = function() {
    this.getId = function(id) {
        return "Hello World";
    },

    this.getAll = function() {
        return "Hello World";
    }
}

BookingFlight.js:

export default var BookingFlight = function() {
    this.book = function() {
        return "Hello World";
    }
}
  1. 然后将它们导入modules.js文件中,并将它们添加到导出对象中:

modules.js:

import BookingHotel from 'BookingHotel.js';
import BookingFlight from 'BookingFlight.js';

module.exports = {
    BookingHotel: BookingHotel,
    BookingFlight: BookingFlight
};