本次打包支持 支持正常的組件調用方式,也支持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 )