功能所需依賴 fs擎勘、glob、ssh2-sftp-clien
新建js文件泌霍,可放至build目錄下
const fs = require('fs')
const glob = require('glob')
const Client = require('ssh2-sftp-client')
const sftp = new Client()
const pluginName = 'SftpPlugin'
class SftpPlugin {
? // dir 本地目錄格式 path.join(__dirname, '..', 'dist/')
? constructor({ dir = '', url = '/', host = '192.168.*.*', port = '22', username = '', password = '', filterFile = null } = {}) { // constructor是一個構造方法货抄,用來接收參數(shù)
? ? this.url = url
? ? this.dir = dir
? ? this.filterFile = filterFile
? ? this.config = {
? ? ? host: host, // 服務器地址
? ? ? port: port,
? ? ? username: username,
? ? ? password: password
? ? }
? }
? apply(compiler) {
? ? if (compiler) {
? ? ? compiler.hooks.done.tap(pluginName, compilation => {
? ? ? ? this.put()
? ? ? })
? ? } else {
? ? ? this.put()
? ? }
? }
? put() { // 自動上傳到FTP服務器
? ? if (!this.dir) {
? ? ? console.error('無法上傳SFTP,請檢查參數(shù)')
? ? ? return
? ? }
? ? sftp.connect(this.config).then(() => { // 連接服務器
? ? ? sftp.list(this.url).then(list => {
? ? ? ? this.deleteServerFile(list).then(() => {
? ? ? ? ? this.globLocalFile()
? ? ? ? })
? ? ? }).catch(err => {
? ? ? ? this.exError(err)
? ? ? })
? ? }).catch(err => {
? ? ? this.exError('sftp連接失敗' + err)
? ? })
? }
? async deleteServerFile(list) { // 刪除服務器上文件(夾)
? ? for (const fileInfo of list) {
? ? ? const path = this.url + fileInfo.name
? ? ? if (fileInfo.type === '-') {
? ? ? ? await sftp.delete(path)
? ? ? } else {
? ? ? ? await sftp.rmdir(path, true)
? ? ? }
? ? }
? ? return new Promise(resovle => {
? ? ? resovle()
? ? })
? }
? globLocalFile() { // 獲取本地路徑所有文件
? ? glob(this.dir + '**', (er, files) => { // 本地目錄下所有文件(夾)的路徑
? ? ? files.splice(0, 1) // 刪除路徑../dist/
? ? ? if (this.filterFile && typeof this.filterFile === 'function') files = files.filter(x => this.filterFile(x))
? ? ? this.uploadFileToSftp(files)
? ? })
? }
? async uploadFileToSftp(files) { // 傳輸文件到服務器
? ? for (const localSrc of files) {
? ? ? const targetSrc = localSrc.replace(this.dir.replace(/\\/g, '/'), this.url)
? ? ? if (fs.lstatSync(localSrc).isDirectory()) { // 是文件夾
? ? ? ? await sftp.mkdir(targetSrc)
? ? ? } else {
? ? ? ? await sftp.put(localSrc, targetSrc)
? ? ? }
? ? }
? ? console.log('已上傳至SFTP服務器!')
? ? sftp.end()
? }
? exError(err) { // 出錯請調(diào)用此方法
? ? sftp.end()
? ? console.error('sftpError:', err)
? }
}
modules.export =?SftpPlugin?
在 項目中的 build/webpack.prod.conf.js 引入
const SftpPlugin = require('./SftpPlugin')
在plugin中
new SftpPlugin({ dir: path.join(__dirname, '..', 'dist/'), url: '/soft/nginx/', host: '192.168.*.*' })
注意: url為sftp服務所對應的你想要上傳的地址,根據(jù)實際情況修改
最后, npm run build 就可以自動部署到ftp服務器了