一、注册npm账号
二、建立gitee仓库
三、设置npm镜像仓库地址
npm config set registry https://registry.npmjs.org/
四、创建本地仓库
-
创建项目
mkdir utils -
创建
lib文件夹, 存放源代码比如index.ts -
进入
utils项目,初始化项目npm init -
修改
package.json中的入口文件 -
安装
typescript,执行命令npm install typescript --save-dev -
初始化
tsconfig.json执行命令npx tsc --init -
生成
tsconfig.json文件后, 修改内容如下
{
"compilerOptions": {
"target": "ESNext", // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'
"module": "ES6", // 指定生成代码的模块系统
"outDir": "./dist", // 指定输出目录
"rootDir": "./lib",
"strict": true, // 启用所有严格类型检查选项
"esModuleInterop": true, // 允许导入非 ES 模块
"declaration": true, // 生成相对应的.d.ts文件
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
},
"include": [
"lib/*"
]
}
- 配置
package.json包基本信息
"type": "module",
- 配置构建输出配置
"main": "dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
package.json文件中新增指令build,如下
"scripts": {
...
"build": "tsc", // 编译 TypeScript
"prepublishOnly": "npm run build" // 发布前自动构建
}
- 创建
.gitignore文件,内容如下
node_modules
登录发布npm包
- 本地登录
npm,执行命令:npm login点击链接登录
当出现
Logged in on https://registry.npmjs.org/.表示登录成功
发布npm 包
npm私仓是收费的, 需要在package.json设置公开如下
// 发布到 npm 的配置
"publishConfig": {
"access": "public", // 公开包
"registry": "https://registry.npmjs.org/" // 官方 registry
},
- 包含的文件列表(发布时会包含这些文件)
"files": ["dist/", ".gitignore", "tsconfig.json", "package.json", "tsconfig.json"],
- 发布
npm publish