从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

相关推荐
丁总学Java3 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
NiNg_1_23410 小时前
npm、yarn、pnpm之间的区别
前端·npm·node.js
奔跑吧邓邓子14 小时前
npm包管理深度探索:从基础到进阶全面教程!
前端·npm·node.js
朗朗乾坤.py1 天前
Hadoop HDFS命令操作实例
hadoop·hdfs·npm
哇咔咔哇咔1 天前
【科普】什么是npm和pip?它们之间有什么异同?
前端·npm·pip
太阳火神的美丽人生1 天前
Vant WeApp 开启 NPM 遇到的问题总结
前端·npm·node.js
Minyy113 天前
小程序-使用npm包
前端·小程序·npm·node.js
Mrs_Lupin3 天前
npm与包
前端·npm·node.js
潜心专研的小张同学3 天前
pnpm依赖安装失败解决|pnpm项目从一个文件夹复制到另一个文件夹运行失败问题解决-以vbenAdmin项目为例
前端·javascript·vscode·npm·vue·pnpm
西西o4 天前
Linux服务安装node,npm与yarn
linux·运维·npm