1.0.95 • Published 10 months ago

hsf-tools v1.0.95

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

Typescript 和 npm 笔记

typescript

命名空间

所谓的命名空间其实就是我们再声明一些 TS 类型的时候为了避免污染全局命名而使用的命名方法:

export namespace Sports {
  export interface Basketball {
    weight: number;
    brand: string;
  }
}

上面这样的命名方法,使得 Basketball 这个类型接口只会在 Sports 这个命名空间内,而不会污染全局的环境。

使用命名空间里的类型:

import { Sports } from "./namespac-test";

export const getBasketBall = (brand?: string): Sports.Basketball => {
  return { brand: brand || "spalding", weight: 200 };
};

自动生成声明文件

我们可以通过配置 ts.config.json 中的编译器配置(compilerOptions) 配置文件来配置自动生成声明文件:

{
  ///
  "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, //是否自动生成声明文件
  "declarationDir": "./" /* Specify the output directory for generated declaration files. */, // 自定义生成的声明文件的目录
  "declarationMap": true /* Create sourcemaps for d.ts files. */, // 是否生成声明文件对应的map文件
  "emitDeclarationOnly": true /* Only output d.ts files and not JavaScript files. */ // 只生成声明文件  不生成JS文件,可以用来发布 @types/* 类型库
  ///
}

模块导出

我们如果自己使用 typescript 编写一个工具库,那么这个库通常会有相对复杂的文件目录结构(也就是说不会是所有的代码逻辑都在一个文件里面),那么我们再到处类型的时候其实可是使用下面的方法将所有的需要导出的模块或者类型从一个文件全部导出:

// 将所有从 ./namespace-test 模块导出的内容从当前模块导出
export * from "./namespac-test";
// 将 "./src/types/football" 模块里面的默认导出的内容从该模块以 MyFootballTypes 这个命名来导出
export { default as MyFootballTypes } from "./src/types/football";
// 将所有的从 ./src/types/football 模块中所有的导出的内容从当前模块导出
export * from "./src/types/football";

npm

配置文件 .npmrc

这个文件可以用来配置 npm 有关的配置,比如:

registry=https://registry.npmjs.org/

那么这个配置就是将 npm 的仓库地址设置为了 https://registry.npmjs.org/,效果同在命令行调用命令设置:

npm config set registry https://registry.npmjs.org

注意:这两种方式的不同点在于:1. 通过配置文件设置的只在当前工程目录中生效,而通过命令行设置的是全局有效的。2. 配置文件的配置优先级大于通过命令行配置的全局配置。

npm 发布包

  1. 首先注册 npm
  2. 在自己的工程中本地打包好,然后使用 npm publish 命令发布到 npm,这里需要注意,每次发布的版本必须不一样,否则会报错。

注意:如果是 typescript 编写的库,那么 package.json 中的入口配置 entry 应该配置为打包后的 js类型的入口文件 的目录地址。

1.0.95

10 months ago

1.0.94

10 months ago

1.0.93

10 months ago

1.0.92

10 months ago

1.0.91

10 months ago

1.0.9

10 months ago

1.0.8

10 months ago

1.0.7

10 months ago

1.0.6

10 months ago

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago