前言

头脑一热想做自己的npm包,但是又无从下手,于是我找到了度娘…看着别人做挺简单,自己上手真难受。一路的坑。注意事项也挺多的,所以我特地详细介绍如何制作自己的npm包,并附上ts类型检测。提升用户体验感。
初次踩坑,我的项目中,如果有不明白的,休要优化的,或者写的不对的,请留言

1.创建项目

Vite 需要 Node.js 版本 14.18+,16+。然而,有些模板需要依赖更高的 Node 版本才能正常运行,当你的包管理器发出警告时,请注意升级你的 Node 版本。
使用vite创建项目

#使用 NPM:
npm create vite@latest
#使用Yarn
yarn create vite
##使用 PNPM:
yarn create vite

【npm】基于vite制作自己的npm包+ts【超详细】-LMLPHP

2.规划目录

└─ customVideo    //前端
  │─ v1
    │─ lib      			  		// 项目打包后的文件
    │─ package      		// 插件文件
    ├─ src       		  	 	// 入口文件 
    ├─ types           	 	// ts类型定义
    ├─ vite              	 	// vite项目配置
    ├─ .gitignore     	 	// git忽略上传清单
    ├─ .npmignore  	 	// npm包上传忽略清单
    ├─ package.json  	// 项目或者模块包的描述
    ├─ README.md     // 项目说明
    ├─ vite.config.ts     // 项目配置
    ├─ tsconfig.build.json      // ts build配置
    └─ tsconfig.json      // ts配置

【npm】基于vite制作自己的npm包+ts【超详细】-LMLPHP

3.配置项目

vite.config.ts相关配置项

import { Plugin ,defineConfig } from 'vite'
import path, { join } from 'path';
import setupPlugins from "./vite/plugins";
import dts from "vite-plugin-dts"
import vue from '@vitejs/plugin-vue'

export default defineConfig(({ command, mode }) => {
  const isBuild = command == 'build'

  return {
    publicPath:"/",
    plugins: [
    vue({ reactivityTransform: true },
        //生成ts声明文件
        dts({
        include:"./package"
    })],
    //设置别名
    resolve: {
      alias: {
        "@/package": join(__dirname, './package/')
      },
      extensions: [".vue",'.js', '.json', '.ts', '.tsx'],//使用别名省略的后缀名
    },
    build: {
      outDir: "lib", //输出文件名称
      lib: {
        entry: join(__dirname, './package/index.ts'), //指定组件编译入口文件
        name: 'vueVideoXg',
        fileName: (format) => `index.${format}.js` // 打包后的文件名
      }, //库编译模式配置
      rollupOptions: {
        // 确保外部化处理那些你不想打包进库的依赖
        external: ["vue"],
        output: {
          // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
          globals: {
            vue: "Vue",
          },
        },
      }, // rollup打包配置
    }
  }

})

tsconfig.json相关配置项

{
  "compilerOptions": {
    "target": "ESNext",
    "noImplicitAny": false, //关闭any提示
    "useDefineForClassFields": true,
    "suppressImplicitAnyIndexErrors":false,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["ESNext", "DOM"],`在这里插入代码片`
    "skipLibCheck": true,
    "paths": {
      "@/*": ["./src/*"],
      "@/package/*": ["./package/*"]
    }
  },
  //需要编译的文件
  "include": [
    "package/**/*.ts",
    "package/**/*.d.ts",
    "package/**/*.tsx",
    "package/**/*.vue"
  ],
  "references": [{ "path": "./tsconfig.node.json" }],
  "exclude": ["node_modules", "lib"]
}

.npmignore相关配置项(设置npm上传忽略目录和文件)

# 忽略目录
.idea
.vscode
scripts/
packages/
public/
node_modules/
src/
types/
vite/

# 忽略指定文件
vite.config.ts
tsconfig.json
.gitignore
*.map

.gitignore相关配置项(设置git上传忽略目录和文件)

node_modules
lib
yarn.lock

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

4.开发组件

【npm】基于vite制作自己的npm包+ts【超详细】-LMLPHP

pagckage/index.ts

import CustomVideo from "./customVideo"
import {App} from "vue";
let comps = [CustomVideo]
const install = (Vue:App) =>{
    comps.map((component:any)=>{
        Vue.component(component.__name as string, component);
    })
}
//使用import.meta.globEager遍历获取文件,会丢失icon图标和style样式
//获取文件
// const components:any = import.meta.globEager('./**/*.vue');
// const install = (Vue:any) =>{
//     for(let i in components) {
//         let component = components[i].default;
//         //注册组件
//         Vue.component(component.__name, component);
//     }
// }

let windowObj = window as any
/* 支持使用标签的方式引入 */
if (typeof windowObj !== 'undefined' && windowObj.Vue) {
    install(windowObj.Vue);
}

export default install

package/customVideo/index.ts

import "./assets/font/iconfont.css"
import "./assets/css/base.less"
import customVideo from "./src/customVideo.vue"

export default customVideo

其他文件代码:https://gitee.com/derekgo

5.发布组件

package.json相关配置项
【npm】基于vite制作自己的npm包+ts【超详细】-LMLPHP

{
  "name": "vue-video-xg",#包名,在npm官网名称中不可重复
  "version": "0.0.19",#项目版本号,每次发布需要修改版本号,不能与历史版本号重复
  "author": "沉默小管",#插件作责
  "description": "vue3自定义视频播放器",#报名描述
  "main": "dist/index.umd.js",#项目入口文件
  "module": "dist/index.es.js",
  "style": "dist/style.css",
  "types": "dist/index.d.ts",#types文件,TS组件需要。
  "files": ["dist"],#发布文件
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",#vue-tsc --noEmit对文件进行类型检查,不进行编译输出
    "preview": "vite preview"
  },
  "dependencies": {
    "less": "^4.1.3",
    "less-loader": "^11.1.3",
    "loader": "^2.1.1",
    "path": "^0.12.7",
    "vite-plugin-compression": "^0.5.1",
    "vite-plugin-dts": "1.4.1",
    "vue": "^3.2.47",
    "vue-video-xg": "^0.0.19"
  },
  "devDependencies": {
    "@types/node": "^20.3.3",
    "@vitejs/plugin-vue": "^4.1.0",
    "typescript": "^5.0.2",
    "vite": "^4.3.9",
    "vue-tsc": "^1.4.2"
  },
  "keywords": [#关键词
    "vue-video",
    "vue-video-xg",
    "vue3",
    "vue3-video"
  ],
  "license": "MIT",#开源协议
  "homepage": "https://gitee.com/derekgo/tool-collection/blob/master/customVideo/vue3/pluginVersion/v1/README.md",
  "repository": "https://gitee.com/derekgo/tool-collection/tree/master/customVideo/vue3/pluginVersion/v1/lib"
}

执行打包命令

yarn build

【npm】基于vite制作自己的npm包+ts【超详细】-LMLPHP

编写README.md文件
README.md源码:源码文件

npm发布
修改好package.json内发布的版本号,然后进入项目根目录,发布项目。
1.登陆

npm login

2.发布

npm publish

6.注意事项

1.不能使用import.meta.globEager遍历获取文件,打包运行后会丢失图标和样式等
2.发布项目前需要修改pacage.json版本号,不能与历史版本重复

7.项目源码

项目源码
打包后源码

07-20 01:10