有些三方js库,没有TS版本,不支持 import 导入。只能自行定义module 进行导入。先使用 yarn 正常安装,然后按下边流程进行配置。
下边以 雪花ID算法举例,如下安装库
yarn add flake-idgen biguint-format
定义 .js
snowFlake.js
/**
* 这里的实现参考 flake-idgen 库中的 readme.md 文件说明
*/
const FlakeId = require('flake-idgen');
const intformat = require('biguint-format')
// 方式一:
class SnowFlake{
constructor(options){
this.flakeIdGen = new FlakeId(options);
}
next() {
return intformat(this.flakeIdGen.next(), 'dec');
}
static getInstance(options) {
if (!SnowFlake._instance) {
SnowFlake._instance = new SnowFlake(options)
}
return SnowFlake._instance
}
}
exports.SnowFlake = SnowFlake;
// 方式二:
// function SnowFlake(options) {
// var flakeIdGen = new FlakeId(options);
// this.next = () =>{
// return intformat(flakeIdGen.next(), 'dec');
// }
// return this
// }
// exports.SnowFlake = SnowFlake;
定义 .d.ts
snowFlake.d.ts 注意要与 .js 文件放在同一目录,且要同名
export interface SnowFlakeOptions {
id?: number;
epoch?: number;
workerId?: number;
datacenterId?: number;
}
// 方式一:
/**
* 使用单实例
* const generator = SnowFlake.getInstance({id: 1, epoch: 1704038400000})
* console.log("generatedId:", generator.next())
* 每次创建新实例
* const generator = new SnowFlake({id: 1, epoch: 1704038400000})
* console.log("generatedId:", generator.next())
*/
export class SnowFlake {
constructor(options?: SnowFlakeOptions);
next(): string;
static getInstance(options?: SnowFlakeOptions): SnowFlake;
}
// 方式二:
/**
* const generator = SnowFlake({id: 1, epoch: 1704038400000})
* console.log("generatedId:", generator.next())
*/
// export function SnowFlake(options: SnowFlakeOptions);
配置 tsconfig.json
增加 allowJs 配置
"compilerOptions": {
"allowJs": true,
},
推荐引用
import {SnowFlake} from '../common/js/snowFlake';
const generator = SnowFlake.getInstance({id: 1, epoch: 1704038400000})
console.log("generatedId", generator.next())