Typescript Node.js 应用程序中的 guid/uuid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43837659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:12:48  来源:igfitidea点击:

guid/uuid in Typescript Node.js app

node.jstypescriptuuidguid

提问by tBlabs

I try to make a uuid(v 3.0.1) package work in Node/Typescript app, but I'm not sure what should I import and how to use it.

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

This is index.d.ts(from @types/uuidv 2.0.29):

这是index.d.ts(来自@types/uuidv 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

I cant find exported class here.

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

For example index.d.tsfrom angular2-uuidlooks like that:

例如index.d.tsangular2-uuid看起来像这样:

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

And it's quite obvious to use:

使用起来很明显:

let id = UUID.UUID();

So. How to use (import and call) uuid?

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

回答by Sergey Yarotskiy

Yes, here is code from my project:

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

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

Note: to install definitions it is required to run

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

npm install --save-dev @types/uuid

回答by Steve Gula

import * as uuid from "uuid";
const id: string = uuid.v4();

回答by GaryO

This also works for me:

这也适用于我:

import uuidv4 from 'uuid/v4'

this.projectId = uuidv4()