从0到1实现一个npm库

项目的目录结构

首先创建一个空项目,

bash 复制代码
npm create vue@lastest
npm i

然后把componentssrc中挪到根目录下,把src改名为examples,修改index.htmlmain.ts的路径。

具体的项目结构如下所示:

  • components
  • examples
  • node_modules
  • public
  • index.html
  • package.json
  • vite.config.ts

导出组件

components/index.ts中定义导出的组件。

以下代码是导出单个组件,

js 复制代码
// components/index.ts
import { App } from 'vue';
import MyButton from './Button';

const MyButtonPlugin = {
  install: (app: App) => {
    app.component('MyButton', MyButton);
  }
}


export default MyButtonPlugin;

如果有多个组件需要导出,

js 复制代码
// components/Button/index.ts
import { App } from 'vue';
import MyButton from './Button';

const MyButtonPlugin = {
  install: (app: App) => {
    app.component('MyButton', MyButton);
  }
}


export default MyButtonPlugin;
js 复制代码
// components/index.ts
import MyButton from "./Button";
import MyTable from "./Table";

const components: any = {
  MyButton,
  MyTable,
};

const MyUI = {
  install: (Vue: App) => {
    Object.keys(components).forEach((key) => {
      Vue.use(components[key]);
    });
  },
};

// 导出多个组件,方便按需引入
export { MyButton, MyTable };

// 全部导出
export default MyUI;

app.use用来安装插件,插件可以是具有install方法的对象,也可以是当作install方法的函数。

引入组件

examples/main.ts中使用app.use来安装插件,然后就可以全局使用了。

js 复制代码
// 整个引入
import MyUI from '../components';

const app = createApp(App);
app.use(MyUI);
js 复制代码
// 按需引入
import { MyButton } from '../components';

const app = createApp(App);
app.use(MyButton);
js 复制代码
// App.vue
<my-button />

打包组件库

首先修改package.json文件,去掉private字段,添加main字段,files字段,

js 复制代码
"main": "dist/index.umd.js",
"files": [
    "dist",
    "components"
  ],

然后修改vite.config.ts配置,

js 复制代码
build: {
    lib: {
      entry: path.resolve(__dirname, "components"),
      name: "MyUI",
      fileName: (format, fileName) => `${fileName}.${format}.js`,
    },
  },

发布库

如果没有npm账号需要先注册一下。

如果npm源不是默认源,需要修改为默认源。

bash 复制代码
npm login
npm publish

注:每次push的时候都要修改package.json中的version

相关推荐
人工智能训练师20 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny0720 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
huangql5201 天前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
风若飞1 天前
npm ERR! code CERT_HAS_EXPIRED
前端·npm·node.js
csdn_aspnet2 天前
Windows、Linux 系统 nodejs 和 npm 版本更新及错误修复
linux·windows·npm·node.js
北城笑笑2 天前
NodeJS 8 ,从 0 到 1:npm 包发布与更新全流程指南( 含多场景适配与踩坑总结 )
前端·npm·node.js·github
码码哈哈0.02 天前
npm : 无法加载文件 C:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚
前端·npm·node.js
阿智@113 天前
推荐使用 pnpm 而不是 npm
前端·arcgis·npm
李游Leo3 天前
npm / yarn / pnpm 包管理器对比与最佳实践(含国内镜像源配置与缓存优化)
前端·缓存·npm
ssshooter4 天前
你知道怎么用 pnpm 临时给某个库打补丁吗?
前端·面试·npm