创建属于自己的组件库

初始化项目

这里我们通过@vue/cli拉取简单配置的模板来初始化一个2.X的项目

vue init webpack-simple vue-test

初始化的项目目录如下

├── README.md
├── index.html
├── package-lock.json
├── package.json
├── src
│   ├── App.vue
│   ├── assets
│   └── main.js
└── webpack.config.js

接下来做一些改动。src目录下新增components用于存放组件,新增一个index.js用于导入组件进行注册,再导出

├── README.md
├── index.html
├── package-lock.json
├── package.json
├── src
│   ├── App.vue
│   ├── assets
│   ├── components
│   ├── index.js
│   └── main.js
└── webpack.config.js

在webpack.config.js同时修改entryoutput,若想区分dev与build,在此处就不在写例子了

entry: './src/index.js',
output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'demo.min.js', 
    library:'lsDemoUI',
    libraryTarget: 'umd',
    umdNamedDefine: true
},

在index.js里注册并导出组件(在每个组件内声明name)

import radio from "./components/c-radio.vue"
import checkbox from "./components/c-checkbox.vue"
import collapse from "./components/c-collapse.vue"
import timeline from "./components/c-timeline.vue"
import dialog from "./components/c-dialog.vue"

const comps=[radio,checkbox,collapse,timeline,dialog] const components={ install(Vue){ comps.map(component=>Vue.component(component.name, component)) } } if(typeof window!=='undefined'&&window.Vue) window.Vue.use(components) export default components

完善package.js,main的路径为dist/demo.min.js 与webpack.config.js里的filename的保持一致

{
  "name": "ls-demo-ui",
  "description": "A Vue.js project",
  "version": "1.6.0",
  "author": "aaron <aaron@mygeno.cn>",
  "license": "MIT",
  "main": "dist/demo.min.js",
  "private": false,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
  }
}

至此已经是一个具备发布到npm的组件库了,如何上传npm和npm私有服务请自行百度

posted @ 2020-08-03 15:07  Aaron英语不好  阅读(246)  评论(0编辑  收藏  举报