【发布时间】:2022-06-21 03:16:38
【问题描述】:
在我的 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 中,我将从每个文件/文件夹中导出所有内容。所以例如在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';
现在,如果我需要从 ServiceA.js 导出的 PageA.jsx 文件中的 ServiceA,我可以按如下方式导入它:
// PageA.jsx
import {
ServiceA
} from 'common';
// ServiceA.js
export class ServiceA {
doStuff () {
// do stuff
}
}
如何设置我的 NodeJS 服务器项目以允许类似的导出和导入?
我想这样做是为了 FE 和 BE 之间的一致性,这样我就可以轻松地将任何 FE 代码移植到我的 BE 项目中,而无需对导出和导入进行任何重大更改。
编辑:我设法使用我授予赏金的 Besworks 的答案让它工作,但是 VS Code Intellisense 不会从导入语句导航到导出定义,直到我添加了一个项目根目录中的jsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#common" : ["./common/index.js"]
}
}
}
【问题讨论】:
标签: javascript node.js reactjs