从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

相关推荐
飞鸟malred10 小时前
vite+tailwind封装组件库
前端·react.js·npm
好运yoo2 天前
npm install的原理
前端·npm
pzpcxy5202 天前
安装VUE客户端@vue/cli报错警告npm WARN deprecated解决方法 无法将“vue”项识别为 cmdlet、函数
前端·vue.js·npm
醉书生ꦿ℘゜এ2 天前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
Revol_C2 天前
【AI+赋能前端-提效篇】开发一个支持项目打包产物本地调试的小工具,已发布到npm!!
前端·npm·ai编程
空中湖2 天前
‘pnpm‘ 不是内部或外部命令,也不是可运行的程序
npm·node.js
孟孟~2 天前
npm run dev 报错:Error: error:0308010C:digital envelope routines::unsupported
前端·npm·node.js
孟孟~2 天前
npm install 报错:npm error: ...node_modules\deasync npm error command failed
前端·npm·node.js
程序猿小D3 天前
第14节 Node.js 全局对象
linux·前端·npm·node.js·编辑器·vim
Jadon_z3 天前
vue2 项目中 npm run dev 运行98% after emitting CopyPlugin 卡死
前端·npm