首页 > 解决方案 > 将其他文件夹中的函数添加到此文件夹中的对象

问题描述

我想创建一个从另一个文件夹导入函数的对象,它看起来像这样:

class = {
  functions: {
    //All functions here
  }
}

这些函数将位于不同的文件夹中,但是,我想制作某种导入器,它会为在文件夹中找到的每个新函数/文件创建新类。

someFunction.js函数文件:

function someFunction() {
   console.log("this is some function");
}

所以我希望看起来像这样:

class.functions.someFunction()

不,我不想将它硬编码到对象中,我想从文件夹中导入所有函数并创建类似的函数。

标签: javascriptnode.js

解决方案


好吧,首先我不想像你想的那样回答你的问题,即使我也认为这不是正确的继续方式。

我还将假设class您所指的不是实际的ES6 Class,而是我们谈论的普通对象。

所以这是代码:

const fs = require('fs');
const path = require('path');

function importer(dirPath) {
    const absoluteDirPath = path.normalize(
        path.isAbsolute(dirPath)
            ? dirPath
            : path.resolve(process.cwd(), dirPath)
    );

    const output = {
        functions: {}
    };

    const content = fs.readdirSync(path.normalize(absoluteDirPath));

    content.forEach((basename) => {
        const absoluteItemPath = path.join(absoluteDirPath, basename);

        if (fs.statSync(absoluteItemPath).isFile() && /\.js$/i.test(basename)) {
            output.functions[basename.slice(-3)] = require(path.relative(
                __dirname,
                absoluteItemPath
            ));
        }
    });

    return output;
}

module.exports = importer;

为此,文件中的所有函数都应导出为:

module.exports = function myFunction() {};

要使用“进口商”,您只需:

const artemis = importer('/path/to/directory'); // PATH MUST BE ABSOLUTE OR RELATIVE TO CWD.

/*
SUPPOSING THAT YOUR DIRECTORY CONTAINS THE FOLLOWING FILES:

function1.js
function2.js

Then you can do:

artemis.function1();
artemis.function2();

Please note that your files must be named in a JS friendly way (a valid string for an object key).

*/

关于这个奇怪方法的最后一个重要说明:这只会在 NodeJS 环境中工作。即使函数可以在其他环境(如浏览器)中工作。下一个方法,在正确的构建过程后适用于任何 ECMAScript 环境:转译(EX:Babel)和捆绑(EX:Webpack)。


建议的解决方案

像现代 JS 库一样使用 ES6 静态导入/导出。这带来了巨大的好处,从静态代码分析到摇树等等。

让我们假设以下层次结构:

//  - index.js
//  - internals/
//    - index.js
//    - module-1.js
//    - module-2.js

internals/module-1.js

function module1() {}

export {module1};

internals/module-2.js

import {module1} from 'module-1.js';

function module2() {
  // YOU CAN USE module1 IF YOU NEED. (AVOID CIRCULAR REFERENCES)
  module1();
}

export {module2};

internals/index.js

import {module1} from './module-1.js';
import {module2} from './module-2.js';

export {module1, module2};

index.js

import * as moduleGroup from './internals/index.js';

export {moduleGroup};

最后,在您导入的地方moduleGroup,您可以执行以下操作:

moduleGroup.module1();
moduleGroup.module2();

显然这是一个基本场景,但恕我直言,这是交付一组功能和其他东西的正确方法。如果您有任何疑问,请告诉我。


推荐阅读