如何从节点js项目中的文件夹递归导出所有内容?

How to recursively export all from folders in node js project?

在我的 React JS 项目中,我配置了一个 jsconfig.json 这样我就可以递归导出嵌套目录并从基目录导入特定导出,如下所示:

jsconfig.json:

{
  "compilerOptions": {
    "jsx": "react",
    "baseUrl": "src"
  }
}

项目文件夹结构:

react-app
  src
    common
    index.js
      services
        ServiceA.js
        ServiceB.js
        index.js
      components
        ComponentA.jsx
        index.js
    pages
      pageA
        PageA.jsx
        index.js
    App.jsx
    index.js
    

现在,在每个 index.js 中,我将从每个 file/folder 中导出所有内容。例如 common/services/index.js:

export * from 'common/services/ServiceA.js';
export * from 'common/services/ServiceB.js';

并且在 common/index.js 中:

export * from 'common/services';
export * from 'common/components';

现在,如果我需要从 PageA.jsx 文件中的 ServiceA.js 导出 ServiceA,我可以按如下方式导入它:

// PageA.jsx
import {
  ServiceA
} from 'common';
// ServiceA.js
export class ServiceA {
  doStuff () {
    // do stuff
  }
}

如何设置我的 NodeJS 服务器项目以允许类似的导出和导入?

我想这样做是为了 FE 和 BE 之间的一致性,这样我就可以轻松地将任何 FE 代码移植到我的 BE 项目中,而无需对导出和导入进行任何重大更改。

永远不要导出所有包。

nodejs module/package import/require 负责所有依赖项和模块缓存。

非常类似于 - https://www.youtube.com/watch?v=-5wpm-gesOY ;)

您可以 map exports 在您的 package.json :

{
  "name": "@your-namespace/your-package",
  ...
  "exports": {
    ".": "./index.js",
    "./common": "./common/index.js"
  }
}

然后你可以按名称引用导出:

import { YourClass } from '@your-namespace/your-package';
import { AnotherClass } from '@your-namespace/your-package/common';

或者,如果您的子模块只需要从您的包中访问,您可以映射 imports 而不是 exports ,这不需要您的包名称前缀,但必须以 [= 开头17=] 字符。您也不需要明确指定每个子模块,您可以使用通配符替换文件夹中的所有内容:

{
  "name": "your-package",
  ...
  "imports": {
    "#common": "./common/index.js",
    "#common/services": "./common/services/index.js",
    "#common/services/*": "./common/services/*.js",
    "#shortcut": "./deeply/nested/path/to/module.js"
  }
}

并使用它们:

import { YourClass } from '#common';
import * from '#common/services';
import { AnotherClass } from '#common/services/ServiceA';
import something from '#shortcut';

在上面的示例中,#common 将是对 ./common/index.js 的引用,而 #common/services/ServiceA 将指向 ./common/services/ServiceA.js

如果您的节点项目在 package.json 中使用 "type": "module",则文件结构完全相同。然而,从 ES 模块中的索引文件导入仍然是一个实验性的标志:

https://nodejs.org/api/esm.html#customizing-esm-specifier-resolution-algorithm

因此您必须使用例如:

来启动它
node --experimental-specifier-resolution=node src/index.js

$ tree src/
src/
├── common
│   ├── index.js
│   ├── ServiceA.js
│   └── ServiceB.js
├── index.js
└── other
    ├── index.js
    ├── OtherA.js
    └── OtherB.js

src/index.js

import { serviceA, serviceB } from './common';
import { otherA, otherB } from './other';

serviceA();
serviceB();
otherA();
otherB();

src/common/index.js

export * from './ServiceA';
export * from './ServiceB';

`src/common/ServiceA.js'

export const serviceA = () => console.log('***** ServiceA');