webpack-自定义plugin

90 阅读1分钟

使用

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) {
        // 1. 监听静态资源被输出到打包目录后的事件
        compiler.hooks.afterEmit.tapAsync('output', async (compilation, callback) => {
            // 获取打包后输出的文件夹地址
            const outputPath = compilation.outputOptions.path;

            // 2. 链接远程服务器
            await this.connectServer();

            // 3. 删除对服务器应目录下的静态资源
            const remotePath = this.options.remotePath;
            await this.ssh.execCommand(`rm -rf ${remotePath}/*`);

            // 4. 上传打包后的静态资源到服务器目录下
            await this.uploadFiles(outputPath, remotePath);

            // 5. 断开服务器链接
            this.ssh.dispose();

            // 6. 执行下一个回调
            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 // 上传并发数
        });
    }
}