从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

相关推荐
Lovely Ruby2 天前
[前端] 封装一下 echart 6,发布到 npm
前端·npm·node.js
BD_Marathon2 天前
NPM_常见命令
前端·npm·node.js
雪域迷影2 天前
怎么将.ts文件转换成.js文件?
javascript·typescript·npm·tsc
安_2 天前
为什么 Vue 要用 npm run dev 启动
前端·vue.js·npm
暴富的Tdy3 天前
【脚手架创建 Vue3 公共组件库】
前端·npm·npm发布
BD_Marathon3 天前
【JavaWeb】NPM_简介和相关配置
前端·npm·node.js
BD_Marathon3 天前
NPM_配置的补充说明
前端·npm·node.js
soul g4 天前
npm 包发布流程
前端·npm·node.js
Y‍waiX‍‍‮‪‎⁠‌‫‎‌‫‬4 天前
【npm】从零到一基于Vite+vue3制作自己的Vue3项目基础的npm包并发布npm
前端·npm·node.js
elangyipi1234 天前
pnpm 深度解析:下一代包管理工具的原理与实践
npm·node.js