guid/uuid 在 Typescript Node.js 应用中

guid/uuid in Typescript Node.js app

我尝试使 uuid (v 3.0.1) 包在 Node/Typescript 应用程序中工作,但我不确定应该导入什么以及如何使用它。

这是index.d.ts(来自@types/uuid v 2.0.29):

declare namespace uuid {
    interface V1Options {
        node?: number[];
        clockseq?: number;
        msecs?: number | Date;
        nsecs?: number;
    }

    type V4Options = { random: number[] } | { rng: () => number[]; }

    interface UuidStatic {
        (options?: V4Options): string;
        (options: V4Options | null, buffer: number[], offset?: number): number[];
        (options: V4Options | null, buffer: Buffer, offset?: number): Buffer;

        v1(options?: V1Options): string;
        v1(options: V1Options | null, buffer: number[], offset?: number): number[];
        v1(options: V1Options | null, buffer: Buffer, offset?: number): Buffer;
        v4: UuidStatic;
        parse(id: string): number[];
        parse(id: string, buffer: number[], offset?: number): number[];
        parse(id: string, buffer: Buffer, offset?: number): Buffer;
        unparse(buffer: number[] | Buffer, offset?: number): string;
    }
}

declare const uuid: uuid.UuidStatic
export = uuid

我在这里找不到导出的 class。

例如 angular2-uuid 中的 index.d.ts 看起来像这样:

export declare class UUID {
    constructor();
    static UUID(): string;
    private static pad4(num);
    private static random4();
}

而且使用起来很明显:

let id = UUID.UUID();

所以。如何使用(导入调用)uuid?

根据测试:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/354cec620daccfa0ad167ba046651fb5fef69e8a/types/uuid/uuid-tests.ts

import uuid = require('uuid');

let uuidv4: string = uuid.v4();

是的,这是我项目中的代码:

import { v4 as uuid } from 'uuid';
const id: string = uuid();

注意:要安装定义,需要 运行

npm install --save-dev @types/uuid
import * as uuid from "uuid";
const id: string = uuid.v4();

这也适用于我:

import uuidv4 from 'uuid/v4'

this.projectId = uuidv4()

我按照以下顺序为我的项目使用uuid

必须安装

npm i --save-dev @types/uuid
npm install uuid

使用uuid包

import { v4 as uuidv4 } from 'uuid';
let myuuid = uuidv4();
console.log('Your UUID is: 'myuuid);