Skip to content

如何引用公用的后端脚本

在实际的应用开发场景中,某个后端脚本会在多个地方被使用到,为了保证代码复用性,支持在后端脚本中引用公用的后端脚本。

被引用后端脚本示例

假设在DEMO项目的/app/ap.app/API创建了后端脚本customUtils.action.ts

ts
//判断传入的值是否为空
export function isEmpty(args:any):boolean{
    if (arg === undefined || arg === null || arg === "") {
		return true;
	}
	let type = typeof (arg);
	if (type === 'number') {
		if (isNaN(arg)) {
			return true;
		}
		return false;
	} else if (type === 'boolean') {
		return false;
	} else if (type === 'object') {
		if (Array.isArray(arg) && !arg.length) {
			return true;
		}
		for (let name in arg) {
			return false;
		}
		return true;
	}
	return false;
}

TIP

其他后端脚本所要引用方法必须要加上export关键字

引入后端脚本

引入公共的后端脚本的写法和TypeScript引入模块的写法类似,以import开头,后面加上需要使用的函数名,加上from关键字,后面加上所要引用的脚本路径。例如:import { isEmpty } from "customUtils.action"

在后端脚本用引用其他后端脚本时需要引用.action文件,即.action.ts编译后的文件。

引用的脚本路径有两种写法,一种是绝对地址,另一种是相对地址。

绝对地址引用

当路径地址以/ 开头时表示为绝对路径。

ts
import { isEmpty } from "/DEMO/app/ap.app/API/customUtils.action";//此时表示引用指定路径下的脚本文件

相对地址引用

当路径以./../开头时表示为相对路径。

  • ./表示目前所在的目录。
  • ../表示上一层目录。可以使用多个,表示上几层目录
ts
import { isEmpty } from "./customUtils.action";//此时表示引用同目录下的customUtils.action文件

引用脚本中多个函数

如果要引入脚本中多个函数,有两种写法

一种是用逗号连接需要使用的函数名

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

另一种是引入整个脚本,在使用时通过别名.函数名的方式使用相关的函数

ts
import customUtils from "customUtils.action";
function test(str:string){
    return customUtils.isEmpty(str);
}
微信公众号微信公众号:山川软件