❧ 使用vite构建npm包
1. vite创建项目
# npmnpm create vite@latest
# yarnyarn create vite
# pnpmpnpm create vite操作步骤:
- Project name: 项目名称
- Select a framework: Others
- Select a variant: create-vite-extra
- select a template: library
- select a variant: TypeScript
2. 项目配置和实现
-
实现源码放在lib目录
-
package.json入库文件修改 -
vite.config.ts生成文件名称修改 -
index.d.ts类型定义文件
3. 设置npm源,否则无法发布
npm config set registry=https://registry.npmjs.org4. 登录npm
npm login5. 发布npm包
npm publish6. 报错解决
-
Remove the ‘private’ field from the package.json to publish it
-
402 Payment Required - PUT https://registry.npmjs.org/@douso%2futils - You must sign up for private packages
# 公开发布npm publish --access public- 带有作用域的包名,如
@douso/utils,需要先创建公开组织 参考地址
7. 使用插件自动生成类型声明
npm install -D vite-plugin-dts配置如下:
export default defineConfig({ build: { lib: { entry: './lib/index.ts', name: 'utils', fileName: 'index' } }, plugins: [dts({ outDir: './dist/types', entryRoot: './lib', })],})