如何发布自己的npm包

发布一个简单的npm包

  1. 首先创建一个文件夹(唯一的命名)
  2. 创建package.json包,输出npm init,一直回车就好。
  3. 创建index.js文件,向外暴露方法。

将包上传或更新到 npm

执行登录命令:npm login

登录npm官网,根据提示输入用户名和密码,邮箱(邮箱必须在注册时进行验证)

发布版本,在登陆命令后接着输入如下命令

javascript 复制代码
npm publish

发布上传后,你可以去 npm 官网上查一下自己的包有没有存在。

在项目中安装你的包

npm i xxx -s,在main.js中引用

在vue项目任何页面使用

发布一个自己组件包

1、在项目中添加组件库文件夹:

在根目录下新建一个plugins文件夹,用来放组件,项目文件结构为:

(我的是跟src平级 创建plugins组件文件夹)

2、添加配置文件

项目根目录下面添加vue.config.js文件,写入以下内容:(主要是配置webpack的打包)

3、编写组件

把封装的组件、封装的指令和封装的过滤器每个都写在分类文件夹中,后面在合理添加并继续封装。下面我以datetime这个组件为例:(是一个时间显示组件)

建组件date-time.vue和单独暴露组件的index.js文件:

date-time.vue内容如下:

javascript 复制代码
<template>
  <div class="date-time" :style="{ 'font-size': `${useStyleObj.fontSize}px` }">
    <p :style="styleObject">{{ nowDate }}</p>
    <p :style="styleObject">{{ nowTime }}</p>
  </div>
</template>
<script>
export default {
  name: "dateTime",
  props: {
    styleObj: {//客户端传递的样式
      type: Object,
      default: () => ({
        fontSize: 25,
        color: ["#dcedff", "#5ca9ff"]
      })
    }
  },
  computed: {
    useStyleObj() {//用computed是为了暴露客户端的styleObj样式属性值可以选填,更加灵活
      let size = 25;
      let color = ["#dcedff", "#5ca9ff"];
      if (this.styleObj.fontSize) {
        size = this.styleObj.fontSize;
      }
      if (this.styleObj.color) {
        color = this.styleObj.color;
      }
      return {
        fontSize: size,
        color: color
      };
    },
    styleObject() {//根据客户端传递的样式值配置文字的渐变色
      return {
        background: `linear-gradient(180deg,${this.useStyleObj["color"][0]},
        ${
          this.useStyleObj.color.length > 1
            ? this.useStyleObj["color"][1]
            : this.useStyleObj["color"][0]
        })`,
        "-webkit-background-clip": "text"
      };
    }
  },
  data() {
    return {
      timer: null,
      nowWeek: "",
      nowDate: "",
      nowTime: ""
      //   styleBox: {}
    };
  },
  created() {
    this.timer = setInterval(() => {
      this.setNowTimes();
    }, 1000); //时间
  },
  beforeDestroy: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    setNowTimes() {//时间拼接方法
      const myDate = new Date();
      const wk = myDate.getDay();
      const yy = String(myDate.getFullYear());
      const mm = myDate.getMonth() + 1;
      const dd = String(
        myDate.getDate() < 10 ? `0${myDate.getDate()}` : myDate.getDate()
      );
      const hou = String(
        myDate.getHours() < 10 ? `0${myDate.getHours()}` : myDate.getHours()
      );
      const min = String(
        myDate.getMinutes() < 10
          ? `0${myDate.getMinutes()}`
          : myDate.getMinutes()
      );
      const sec = String(
        myDate.getSeconds() < 10
          ? `0${myDate.getSeconds()}`
          : myDate.getSeconds()
      );
      const weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const week = weeks[wk];
      this.nowDate = `${yy}/${mm}/${dd} ${week}`;
      this.nowTime = `${hou}:${min}:${sec}`;
      this.nowWeek = week;
    }
  }
};
//样式文件
</script>
<style lang="scss" scoped></style>

index.js文件内容:为组件提供 install 方法,供组件对外按需引入

javascript 复制代码
import dateTimes from "./date-time.vue";

dateTimes.install = Vue => Vue.component(dateTimes.name, dateTimes); //注册组件

export default dateTimes;

这个单独暴露组件的 index.js,意思是如果这个工程值封装一个组件使用的话,就用这个index.js 文件暴露 install 即可了。

plugins 文件夹下面新建一个 index.js 文件,为了统一导出所有组件及暴露 install 方法。之前的 index.js 只是安装单个组件,而现在这个 index.js 是循环安装所有组件、所有指令、过滤器统一暴露出去,可以按需引用组件,此时plugins文件夹的内容为:

我这里是统一暴露组件、指令、过滤器:

javascript 复制代码
//组件
import DateTime from "./components/dateTime/date-time.vue"

//所有组件列表
const components = [DateTime]


//定义install方法,Vue作为参数
const install = Vue => {
  //判断是否安装,安装过就不用继续执行
  if (install.installed) return
  install.installed = true
  //遍历注册所有组件
  components.map(component => Vue.component(component.name, component))
}

//检测到Vue再执行
if (typeof window !== "undefined" && window.Vue) {
  install(window.Vue);
}
export default {
  install,
  //所有组件,必须具有install方法才能使用Vue.use()
  ...components
}

4、在本地页面中使用组件

在main.js中引入

在页面中不用引入使用使用组件,因为是全局注册了组件库,所以可以直接使用标签,这个标签与组件文件中的date-time.vue里的name保持一致,只不过一个是驼峰式写法,一个是标签名称。

测试可以全局使用组件,说明封装的组件没有问题,下面可以打包了。

5、打包

在package.json文件中的"scripts"字段里添加以下内容:

javascript 复制代码
"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lib": "vue-cli-service build --target lib --name 包名 -dest lib plugins/index.js",
    "lint": "vue-cli-service lint"
  },

因为在vue-cli中,可以通过以下命令将一个单独的入口打包成库

// target: 默认为构建应用,改为 lib 即可启用构建库模式

// name: 输出文件名

// dest: 输出目录,默认为 dist,这里我们改为 lib

// entry: 入口文件路径

vue-cli-service build --target lib --name lib [entry]

package.json中配置打包信息:

  • .gitignore文件中添加:
  • 把包的一些测试文件过滤掉,最终打包只留下直接封装的文件,即plugins中封装的暴露组件

在终端执行npm run lib 即可,执行结果:

6、发布包

7、使用包

npm i xgs_common -s

在项目文件mainjs中引入。

在项目中直接使用组件中的name即可

例如:<date-time/>

相关推荐
.生产的驴几秒前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
awonw3 分钟前
[前端][easyui]easyui select 默认值
前端·javascript·easyui
九圣残炎24 分钟前
【Vue】vue-admin-template项目搭建
前端·vue.js·arcgis
柏箱1 小时前
使用JavaScript写一个网页端的四则运算器
前端·javascript·css
TU^1 小时前
C语言习题~day16
c语言·前端·算法
学习使我快乐014 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
bobostudio19954 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
黄尚圈圈5 小时前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
浮华似水6 小时前
简洁之道 - React Hook Form
前端