Skip to content

引用公共的后端脚本文件

多个后端脚本需要复用同一段逻辑时,可以把公共函数放在独立的 .action.ts 文件中,再由其他后端脚本通过 import 引用。这样可以减少重复代码,并让通用校验、格式转换、接口封装等逻辑集中维护。

本文以 DEMO 项目中 /app/ap.app/API/customUtils.action.ts 为例,说明如何导出公共函数并在其他后端脚本中引用。

编写可被引用的后端脚本

在公共后端脚本中,需要被其他脚本引用的函数必须使用 export 导出。

ts
export function isEmpty(arg: any): boolean {
  if (arg === undefined || arg === null || arg === "") {
    return true;
  }

  const type = typeof arg;
  if (type === "number") {
    return isNaN(arg);
  }
  if (type === "boolean") {
    return false;
  }
  if (type === "object") {
    if (Array.isArray(arg) && !arg.length) {
      return true;
    }
    for (const name in arg) {
      return false;
    }
    return true;
  }
  return false;
}

提示

只有使用 export 导出的函数、变量或对象,才能被其他后端脚本通过 import 引用。

引用后端脚本

在后端脚本中引用公共脚本时,写法和 TypeScript 模块导入类似:

ts
import { isEmpty } from "customUtils.action";

需要注意的是,from 后面引用的是 .action 文件,而不是 .action.ts 源文件。.action.action.ts 编译后的后端脚本文件。

使用绝对路径引用

当脚本路径以 / 开头时,表示从元数据根路径开始查找。

ts
import { isEmpty } from "/DEMO/app/ap.app/API/customUtils.action";

绝对路径适合引用位置固定、需要被多个目录下脚本复用的公共文件。

使用相对路径引用

当脚本路径以 ./../ 开头时,表示从当前脚本所在目录开始查找。

ts
import { isEmpty } from "./customUtils.action";

相对路径常用于引用同目录或邻近目录中的公共脚本:

写法含义
./customUtils.action引用当前目录下的 customUtils.action
../common/customUtils.action引用上一级目录中 common 目录下的 customUtils.action

引用多个函数

如果只需要引用公共脚本中的部分函数,可以在 {} 中列出函数名:

ts
import { isEmpty, isBoolean } from "customUtils.action";

如果需要使用公共脚本中的多个导出内容,也可以给整个脚本设置别名,再通过 别名.函数名 调用:

ts
import * as customUtils from "customUtils.action";

function test(str: string) {
  return customUtils.isEmpty(str);
}

使用建议

  1. 公共脚本文件名保持简短清晰,例如 customUtils.action.tscommon.action.ts
  2. 公共函数要明确输入参数和返回值类型,避免调用方猜测数据结构。
  3. 被多个应用或多个目录复用的脚本,优先使用稳定的绝对路径引用。
  4. 只在局部目录内复用的脚本,优先使用相对路径引用,便于整体移动目录。
微信公众号微信公众号:山川软件