On-demand require()

前端 未结 2 1533
迷失自我
迷失自我 2021-01-22 08:22

Say I create a library in ./libname which contains one main file: main.js and multiple optional library files which are occasionally used with the main

相关标签:
2条回答
  • 2021-01-22 08:57

    Looks like the only way is to use getters. In short, like this:

    exports = {
        MainClass : require('main.js').MainClass,
        get a(){ return require('./a.js'); },
        get b(){ return require('./a.js'); }
    }
    
    0 讨论(0)
  • 2021-01-22 09:03

    This may possible if you called the "MainClass" to dynamically load the additional modules on-demand. But I suspect this will also mean an adjustment in the api to access the module.

    I am guess your motivation is to "avoid" the extra processing used by "non-required modules". But remember Node is single threaded so the memory footprint of loading a module is not per-connection, it's per-process. Loading a module is a one-off to get it into memory.

    In other words the modules are only ever loaded when you start your server not every-time someone makes a request.

    I think you looking at this from client-side programming where it's advantages to load scripts when they are required to save on both processing and or http requests.

    On the server the most you will be saving is few extra bites in memory.

    0 讨论(0)
提交回复
热议问题