本文共 1151 字,大约阅读时间需要 3 分钟。
我们首先使用 vue-cli 初始化一个项目:
npm install -g @vue/clivue create cuclife
创建项目后,我们需要调整项目结构:
src 文件夹改名为 examples,并在项目根目录下创建一个 packages 文件夹。packages 文件夹将用于存放我们要发布的组件包。由于我们修改了项目结构,启动 Vue 项目可能会报错。为解决这个问题,我们需要修改 vue.config.js:
module.exports = { pages: { index: { entry: 'examples/main.js', template: 'public/index.html', filename: 'index.html' } }} packages 文件夹中编写组件假设我们正在开发一个叫 doAlert 的组件,存放在 packages/doAlert 文件夹中。我们需要创建以下文件:
index.jsimport doAlert from './src/main'doAlert.install = function(Vue) { Vue.component(doAlert.name, doAlert)}export default doAlert main.vue接下来,我们需要将组件包发布到 npm:
packages/doAlert 文件夹:cd packages/doAlert
npm init -ynpm install vue
package.json:{ "name": "do-alert", "version": "1.0.0", "description": "A Vue.js alert component", "main": "index.js", "scripts": { "prepare": "vue build packages/doAlert/main.vue" }} npm publish
在其他项目中使用:
npm install do-alert
然后在 Vue 项目中使用:
import { doAlert } from 'do-alert'doAlert.install(Vue) 转载地址:http://aqjfk.baihongyu.com/