首页 > 技术文章 > vue组件的 npm 打包发布

cbingqin 2020-12-22 16:41 原文

本次打包支持 支持正常的组件调用方式,也支持Vue.use, 也可以直接引用打包好的js文件
第一步:创建一个简单项目(我的项目名称vue-excel-upload)使用 vue init webpack-simple vue-excel-upload 
按需选择或填入项目信息,创建完项目,使用npm install , npm run dev 要能让项目跑起来,说明项目创建成功
第二步:在src目录下新建components文件夹,此文件夹下创建Excel.vue
Excel.vue就是我们要用来写组件,如下Excel.vue文件内容:

<template>
  <div>
    <el-dialog v-if="dialogVisible" title="Upload Excel" :visible.sync="dialogVisible" width="40%" :before-close="cancle">
      <el-upload
        class="ml-10"
        :limit="limitNum"
        :auto-upload="false"
        accept=".xlsx"
        :action="UploadUrl()"
        :before-upload="beforeUploadFile"
        :on-change="fileChange"
        :on-exceed="exceedFile"
        :on-success="handleSuccess"
        :on-error="handleError"
        :file-list="fileList"
      >
        <el-button slot="trigger" size="mini" type="primary">Browse</el-button>
        <div slot="tip" class="el-upload__tip">Only xlsx files can be uploaded, and the file size is less than 100M</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">Cancle</el-button>
        <el-button type="primary" @click="uploadFile">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    dialogVisible: Boolean
  },
  data() {
    return {
      limitNum: 1, // 上传excell时,同时允许上传的最大数
      fileList: [] // excel文件列表
    }
  },
  methods: {
    UploadUrl() {
      // 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,所以这里将action设置为一个返回为空的方法就行,避免抛错
      return ''
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择 ${this.limitNum} 个文件`
      )
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.fileList = []
      this.fileList.push(file.raw)
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
    beforeUploadFile(file) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024
      if (extension !== 'xlsx') {
        this.$message.warning('Upload files with the suffix .xlsx')
      }
      if (size > 100) {
        this.$message.warning('The file size is less than 100M')
      }
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$message.success('Upload successful')
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error('Upload failed')
      console.log(err)
    },
    uploadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning('Please upload the file')
      } else {
        const form = new FormData()
        form.append('file', this.fileList[0])
        this.$emit('uploadFile', form)
        this.fileList = []
      }
    },
    cancle() {
      this.$emit('cancle', false)
    }
  }
}
</script>

<style scoped>
</style>

第三步:在webpack.config.js同级目录(也是该组件的根目录)下新建 index.js文件index.js是把Excel.vue文件暴露出去的出口,index.js文件内容如下:

import Excel from './src/components/Excel'
import _Vue from 'vue'

Excel.install = Vue => {
if (!Vue) {
window.Vue = Vue = _Vue
}
Vue.component(Excel.name, Excel)
}
export default Excel;

第四步:修改package.json

修改private为false才能被其他人使用,添加mains用来项目引进时能直接跳到打包目录dist下的excel-upload.js中
"private": false,
"main": "dist/excel-upload.js",

第五步:修改 webpack.config.js
修改module.exports中的入口entry和出口output
入口会根据开发环境 ,生产环境切换

var path = require('path')
var webpack = require('webpack')
const NODE_ENV = process.env.NODE_ENV

module.exports = {
  // entry: './src/main.js',
  entry:NODE_ENV === 'development'?'./src/main.js':'./src/index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'excel-upload.js',
    library: 'excel-upload',
    libraryTarget: 'umd',
    umdNamedDefine:true
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      },
      {test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
        loader: 'file-loader'}
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

第六步:如需本地预览,应在App.vue中引入改组件,使用npm run dev,便可预览组件
App.vue页面

<template>
  <div>
    <Excel :dialog-visible="dialogVisible" @cancle="cancle" @uploadFile="uploadFile" />
  </div>
</template>

<script>
import Excel from './components/Excel'
export default {
  components:{
      Excel
    },
    data(){
      return {
        dialogVisible: true
      }
    },
    methods: {
      cancle(dialogVisible) {
      this.dialogVisible = dialogVisible
      },
      uploadFile(form){
        //请求上传接口
        console.log('请求上传接口')
        const formData = new FormData()
        formData.append('file', form)
        console.log(formData)
      }
    }

}
</script>

<style>

</style>

第七部:跟目录index.html页面修改
修改index.html的js引用路径,因为我们修改了output 的 filename,所以引用文件的名字也得变

<script src="/dist/excel-upload.js"></script>

---------------到此步骤,组件的开发和配置已近完成,下面进行npm打包----------------------
npm打包
第一步:上官网注册一个npm账号(必须邮箱验证通过的账号才能使用)https://www.npmjs.com/
第二步:登录并发布
npm login   
 登录账号信息,按要求填入账号信息
npm publish 
发布到npm上
---------------------组件的引入与使用------------------------------------------------
第一步:下载组件 
 npm install vue-excel-upload
第二步:引入组件   
去main.js文件中引入:
import  ExcelUpload  from 'vue-excel-upload'
Vue.use(ExcelUpload )



 

 

推荐阅读