从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

相关推荐
渔夫阿布13 小时前
在MAC上面通过HomeBrew安装node和npm@指定版本
前端·macos·npm
雲小妖1 天前
PowerShell 执行策略:fnm管理软件安装nodejs无法运行npm,错误信息:about_Execution_Policies
前端·npm·node.js
qq_530245191 天前
nvm下载node版本npm下载失败
前端·npm·node.js·nvm
Winson℡1 天前
在使用 npm link 进行本地 npm 包调试时,是否需要删除项目中已安装的依赖包取决于你的调试场景和依赖管理方式
前端·npm·node.js
AlgorithmAce2 天前
解决npm/yarn等包管理工具在vscode中使用出现系统禁止运行脚本的情况
前端·npm·node.js
超级无敌谢大脚2 天前
前端包管理工具进化论:npm vs yarn vs pnpm 深度对比
前端·npm·node.js
Merlyn103 天前
npm : 无法加载文件 E:\ProgramFiles\Nodejs\npm.ps1,因为在此系统上禁止运行脚本。
前端·npm·node.js
一个打工仔的笔记3 天前
npm i 失败权限问题
前端·npm·node.js
heroboyluck3 天前
rust 前端npm依赖工具rsup升级日志
前端·rust·npm
HugeYLH4 天前
解决npm问题:错误的代理设置
前端·npm·node.js