自定义Vue组件打包、发布到npm以及使用

本文将帮助:将自己写的Vue组件打包到npm进行代码托管,以及正常发布之后如何使用自己的组件。

  本文讲述的仅仅是最基础的实现,其他复杂的操作需要非常熟悉webpack的相关知识,作者将继续学习。


  先附上大佬的文献:https://blog.csdn.net/qq_40513881/article/details/82494958

  按照大佬文中写的一步步操作,够细心的话基本可以一步到位。下面总结一下发布步骤:

  1. 利用Vue的脚手架新建一个简易版的Vue项目my-project:

  vue init webpack-simple my-project -> cd my-project -> npm i -> npm run dev

  2. 编写组件:

  src下新建myPlugin文件夹用于存放所以开发的组件 -> 为每一个组件创建一个文件夹,其中存放一个vue组件文件和一个index.js配置文件 -> 在myPlugin下的最外层创建一个入口配置文件 -> 为每个人vue组件文件中加上一个name属性

  3. 测试组件:

  在app.vue中测试一下自己的组件可不可以用

  4. 编写配置文件

  为刚刚加入的每个组件文件夹中的index.js放入如下代码:(其中ldcPagination为组件名)

import ldcPagination from './index.vue';
ldcPagination.install = Vue => Vue.component(ldcPagination.name, ldcPagination);//.name就是开始说的vue文件暴露出来的name名,ldcPagination整个组件
export default ldcPagination;

  为myPlugin下index.js放入如下代码:(其中ldcPagination为组件名,多个组件直接在components数组中加入并在最后输出出来就行)(引入的公共样式文件等都可以放这个文件中

import ldcPagination from './Pagination/index.js';
const components = [
    ldcPagination
]
const install = function(Vue, opts = {}) {
    components.forEach(component => {
        Vue.component(component.name, component);
    });
}
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}
 
export default {
    install,
    ldcPagination
}

  5. 改写webpack.config.js配置文件

  将其中的输入输出换成如下代码:

var path = require('path')
var webpack = require('webpack')
const NODE_ENV = process.env.NODE_ENV;
module.exports = {
//entry: './src/main.js',
//output: {
//      path: path.resolve(__dirname, './dist'),
//      publicPath: '/dist/',
//      filename: 'build.js'
//    },
     entry: NODE_ENV == 'development' ? './src/main.js' : './src/myPlugin/index.js',
     output: {
         path: path.resolve(__dirname, './dist'),
         publicPath: '/dist/',//路径
         filename: 'ldc-ui.js',//打包之后的名称
         library: 'ldc-ui', // 指定的就是你使用require时的模块名
         libraryTarget: 'umd', // 指定输出格式
         umdNamedDefine: true // 会对 UMD 的构建过程中的 AMD 模块进行命名。否则就使用匿名的 define
     },
...
}

  6. 发布前准备

  改写package.json中的private为false,加入"main": "dist/ldc-ui.js", 其他的自定义 -> 新建.npmignore文件忽略不需要上传的文件如.* *.md *.yml build/ node_modules/ src/ test/

  7. 发布

  npm run build 打包 -> 注册npm账号 -> npm login 登录 -> npm publish 发布

 

  可能出现问题

1. 登录源错误, npm config get registry 可查看当前登录源,npm config set registry=http://registry.npmjs.org 可切换到正确的登录源

2. 版本号不能重复

3. 图片资源打包后无法使用,所以自己的组件中不要使用

  使用组件方式

1. npm i xxx -D

2. import XXX from 'xxx'

3. const { A, B } = XXX

4. 在Vue中注册 components: { A, B }

 

猜你喜欢

转载自www.cnblogs.com/eightFlying/p/publishToNpm.html