# 发布一个ts编写的npm包
# 概述
前面我们已经学习了ts的基础知识,而且学习了tsconfig.json
的配置,那么接下来我们从零开始发布一个用ts
编写的简单的npm
包。
# 项目初始化
首先我们使用npm init
初始话一个项目。
{
"name": "array-map-typescript",
"version": "1.0.0",
"description": "array-map-function by using typescript",
"main": "./dist/array-map-typescript.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"typescript"
],
"author": "xxx",
"license": "MIT",
"devDependencies": {
"typescript": "^3.8.3"
}
}
这里最主要的是设置入口文件main
,注意这里的入口文件是我们发布的npm
包的入口文件,也就是说是我们打包后的文件,而不是我们当前创建的项目的入口文件。
# 引入typescript
想要在项目中使用typescript
,需要我们使用tsc -- init
创建一个tsconfig.json
配置文件。
{
"compilerOptions": {
/* Basic Options */
// "incremental": true,
"target": "es6",
"module": "commonjs",
"declaration": true,
// "outFile": "", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files.
"strict": true, /* Enable all strict type-checking options. */
},
"exclude": [
"./dist",
"example"
]
}
配置文件中,我们需要进行一些简单的设置。比如exclude
我们需要排除一些不需要编译的ts文件,以及ts打包后的输出文件"outDir": "./dist"
。outDir
是打包后的ts的输出目录。
# 编写ts
使用ts
实现一个简单的功能。
## arr-map.ts
const arrMap = <T,U>(
array:T[],
callback:(item:T,index:number,arr:ReadonlyArray<T>) => U) :U[] => {
let i = 0;
const resultArr = [];
const len = array.length;
while(i < len){
resultArr.push(callback(array[i],i,array));
i++;
};
return resultArr;
};
export = arrMap;
使用tsc
进行编译,会将文件编译打包到dist
目录中。接下来就是将这个包发布到npm平台。
# 发布ts编写的npm包
- 创建
.npmignore
文件忽略不需要发布的文件
example/
test/
node_modules/
2.登陆并发布
npm login // 这里会要求输出一些信息,比如username,password
npm publish
一些可能影响发布的注意事项:
- 如果npm平台上存在重名的项目,在会导致发布失败。
- 如果使用了taobao镜像,则需要将镜像重新切换回来。
- 如果需要更新npm包,每次更新都需要修改版本。