vue日常-第一个vue自定义插件demo

1.利用脚手架初始化

# 安装vue脚手架
npm install vue-cli -g

# 初始化项目
vue init webpack-simple vue-first-demo
cd vue-first-demo
npm install
npm run dev

2.调整结构(借鉴element-ui)

组件实现请参考插件开发

tree

│  .babelrc
│  .editorconfig
│  .gitignore
│  a.txt
│  index.html
│  package-lock.json
│  package.json
│  README.md
│  webpack.config.js
├─node_modules
└─src
    └─package
        │  main.js                # 所有组件入口
        └─c-table                 # c-table组件模块目录
            │  index.js           # c-table组件入口
            └─src                 # c-table组件源码目录
                    main.vue      # c-table组件

3.配置webpack编译入口与出口

var path = require('path')
var webpack = require('webpack')

module.exports = {
  // 入口改成我们自定义后的入口
  entry: './src/package/main.js',
  output: {
    // 输出的路径
    path: path.resolve(__dirname, './lib'),
    publicPath: '/lib/',
    // 输出的文件名
    filename: 'build.js',
    chunkFilename: '[id].js',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
}

4.配置package.json对外暴露组件

# 注意:json里面的中文部分为注释,因为json不支持注释
{
  "name": "vue-first-demo",
  "description": "A Vue.js project",
  "version": "1.0.0",
  "author": "luotao <luotao@gutou.com>",
  "license": "MIT",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
  },
  "dependencies": {
    "vue": "^2.5.11"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ],
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "babel-preset-stage-3": "^6.24.1",
    "cross-env": "^5.0.5",
    "css-loader": "^0.28.7",
    "file-loader": "^1.1.4",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "vue-loader": "^13.0.5",
    "vue-template-compiler": "^2.4.4",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.9.1"
  },
  "标记为公有库": "",
  "private": false,
  "协议": "",
  "license": "MIT",
  "main: lib/build.js 配置意思是,别人用这个包 import xxxx from 'xxxx'; 时,引入的文件。": "",
  "main": "lib/build.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/yucccc/vue-pay-keyboard"
  }
}

5.编译打包

npm run build

6.发布到npm

# 添加用户,填写自己的信息然后回车
npm add user

# 查看当前用户
npm whoami

# 登录
npm login

# 发布
npm publish

7.使用

# 在需要引用组件的项目执行
npm install vue-first-demo

# 导入使用组件
import VueFirstDemo from 'vue-first-component-demo'

# 安装插件
Vue.use(VueFirstDemo)

# 在模块中引用组件
<c-table/>

发表评论