webpack打包後自動發佈插件UploadPlugin(以上傳到七牛網爲例)

打包後自動發佈

UploadPlugin.js
class UploadPlugin {
    constructor(options) {
        let {bucket = '', domain = '', accessKey = '', secretKey = ''} = options;
        let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
        var putPolicy = new qiniu.rs.PutPolicy({scope: bucket});
        this.uploadToken=putPolicy.uploadToken(mac);
        let config = new qiniu.conf.Config();
        this.formUploader = new qiniu.form_up.FormUploader(config);
        this.putExtra = new qiniu.form_up.PutExtra();
    }

    apply(compiler) {
        compiler.hooks.afteremit.tapPromise('UploadPlugin', (compilation) => {
            let assets = compilation.assets;
            let promises = [];
            Object.keys(assets).forEach(filename => {
                promises.push(this.upload(filname));
            });
            return Promise.all();
        })
    }

    upload(filename) {
        return new Promise((resolve, reject) => {
            let localFile = path.resolve(__dirname, '../dist', filename);
            this.formUploader.putFile(this.uploadToken, filename, localFile, this.putExtra, (respErr, respBody, respInfo) => {
                if (respErr) {
                    reject(respErr);
                }
                if (respInfo.statusCode == 200) {
                    sesolve(respBody);
                }
            });
        })
    }
}

module.exports = UploadPlugin;

webpack.config.js
let webpack = require('webpack');
let path = require('path');
let DonePlugin = require('./plugins/DonePlugin');
let AsyncPlugin = require('./plugins/AsyncPlugin');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let FileListPlugin = require('./plugins/FileListPlugin');
let MiniCssExtractPlugin = require('mini-css-extract-plugin');
let InlineSourcePlugin = require('./plugins/InlineSourcePlugin');
let UploadPlugin = require('./plugins/UploadPlugin');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        // publicPath: "", 資源
    },
    mode: 'development',
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'main.css'
        }),
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        }),
        new FileListPlugin({
            filename: 'list.md',
        }),
        // new InlineSourcePlugin({
        //     match: /\.(js|css)$/,
        // })
        // 上傳到七牛
        new UploadPlugin({
            bucket: '', // 桶
            domain: "",     // 域名
            accessKey: '',  //
            secretKey: '',  //
        })
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            }
        ]
    }
}
;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章