如何通过index.ts统一导出Shopify目录模块实现批量导入?
问题描述
我的目录结构如下:
controllers --shopify ---webhook.ts ---auth.ts ---products.ts --index.ts
我希望在shopify目录下创建一个index.ts文件,统一导出该目录下所有文件的导出项,以便后续使用如下方式导入:
import { ShopifyWebhook, Auth, Product } from 'controllers/shopify';
而非每次单独导入每个文件:
import { ShopifyWebhook } from 'controllers/shopify/webhook.ts'; import { Auth } from 'controllers/shopify/auth.ts'; import { Product } from 'controllers/shopify/products.ts';
以下是webhook.ts的示例代码:
import { Request, Response } from "express"; import * as Sentry from '@sentry/node'; import { shopify } from "src/server"; // Process webhooks export const ShopifyWebhook = async (req: Request, res: Response) => { try { // Note: the express.text() given above is an Express middleware that will read // in the body as a string, and make it available at req.body, for this path only. await shopify.webhooks.process({ rawBody: req.body, // is a string rawRequest: req, rawResponse: res, }); console.log('PROCESS'); } catch (e) { Sentry.captureException(e); } };
请问我能否按如下方式编写shopify/index.ts?
export { Webhook } from 'controllers/shopify/webhook'; // 其他文件也类似导出?
解决方案
完全可以通过创建shopify/index.ts实现统一导出,但需要注意导出名称必须与对应文件里的实际导出名称一致。
根据你提供的webhook.ts示例,文件内导出的是ShopifyWebhook而非Webhook,因此需要对应调整。正确的shopify/index.ts写法如下:
// 从webhook.ts导出实际的ShopifyWebhook export { ShopifyWebhook } from './webhook'; // 若想简化名称为Webhook,可使用重命名导出: // export { ShopifyWebhook as Webhook } from './webhook'; // 假设auth.ts中导出的是Auth export { Auth } from './auth'; // 假设products.ts中导出的是Product export { Product } from './products';
配置完成后,你就能直接通过import { ShopifyWebhook, Auth, Product } from 'controllers/shopify';(若使用重命名则替换为Webhook)导入所需项。
额外注意:
- 路径使用相对路径
./webhook即可,无需写完整绝对路径,因为index.ts与目标文件处于同一目录。 - 务必保证导出名称与原文件的导出标识符完全匹配,否则会出现导入错误。
内容的提问来源于stack exchange,提问作者Ömer Ok
相关产品推荐
相关产品推荐

