从零开始编写公共组件

285 阅读1分钟

1. 创建vue项目

2. 编写组件

3. 编写index.js文件,整合组件,对外导出

// index.js
import SelectOrganize from "./select-organize/index.vue";

export function install(Vue, options) {
  if (install.installed) return;

  install.installed = true;

  if (!options || options.SelectOrganize) {
    Vue.component(SelectOrganize.name, SelectOrganize);
  }
}

// Create module definition for Vue.use()
const plugin = {
  install,
};

// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null;
if (typeof window !== "undefined") {
  GlobalVue = window.Vue;
} else if (typeof global !== "undefined") {
  GlobalVue = global.Vue;
}
if (GlobalVue) {
  GlobalVue.use(plugin);
}

export default {
  SelectOrganize,
  install,
};

4. 编写npm脚本。--target:构建目标为lib库模式,--dest:输出目录,–name:打包后的文件名前缀

// package.json
"scripts": {
    "build": "vue-cli-service build --dest=lib --target=lib --name=common-h5 src/components/index.js",
  }

5. npm run build,生成lib文件夹。

9.png

6. 配置package.json的main入口文件,并将项目推到gitLab

10.png

7. 在其它项目安装公共组件。该方式适合安装公司内部的git服务器上的项目

npm install -S git+http://name:pw@888.88.88.88:8888/web/common-h5-components.git#master

8. 使用组件。需要引入样式文件

import CommonH5Components from 'common-h5-components';
import 'common-h5-components/lib/common-h5.css'
Vue.use(CommonH5Components);