使用
module.exports = {
plugins: [
new AutoUploadWebpackPlugin({
host: '你服务器ip地址',
username: '用户名',
password: '用户密码',
remotePath: '打包后的文件上传到服务器的那个路径'
})
]
}
插件实现
const { NodeSSH } = require('node-ssh');
class AutoUploadWebpackPlugin {
constructor(options) {
this.ssh = new NodeSSH();
this.options = options;
}
apply(compiler) {
compiler.hooks.afterEmit.tapAsync('output', async (compilation, callback) => {
const outputPath = compilation.outputOptions.path;
await this.connectServer();
const remotePath = this.options.remotePath;
await this.ssh.execCommand(`rm -rf ${remotePath}/*`);
await this.uploadFiles(outputPath, remotePath);
this.ssh.dispose();
callback();
});
}
async connectServer() {
await this.ssh.connect({
host: this.options.host,
username: this.options.username,
password: this.options.password
});
}
async uploadFiles(localPath, remotePath) {
await this.ssh.putDirectory(localPath, remotePath, {
recursive: true,
concurrency: 10
});
}
}