upload.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const OSS = require('ali-oss');
  2. const queue = require('queue');
  3. const fs = require('fs');
  4. const path = require('path');
  5. let client = new OSS({
  6. region: 'oss-cn-shenzhen',
  7. accessKeyId: 'LTAI5tCtRs8DXBLBsn49qRZX',
  8. accessKeySecret: '86uC18LZsfB9JU04BK7ImVXfOytEkG',
  9. bucket: '9space-2021'
  10. });
  11. class UploadCDNPlugin {
  12. constructor(basePath) {
  13. this.basePath = basePath + '/';
  14. }
  15. // Define `apply` as its prototype method which is supplied with compiler as its argument
  16. apply(compiler) {
  17. compiler.hooks.done.tapAsync('UploadPlugin', (stats, callback) => {
  18. let basePath = this.basePath;
  19. const q = queue({ results: [], concurrency: 16 });
  20. function uploadDir(dir) {
  21. fs.readdirSync(dir).forEach(child => {
  22. if (/^\./.test(child)) return;
  23. let file = path.resolve(dir, child);
  24. let stat = fs.statSync(file);
  25. if (stat.isDirectory()) {
  26. uploadDir(file);
  27. } else {
  28. q.push(async cb => {
  29. let relpath = path.relative(path.resolve(__dirname, 'dist'), file);
  30. const result = await client.put(path.normalize(basePath + relpath), file);
  31. console.log(result);
  32. cb();
  33. });
  34. }
  35. });
  36. }
  37. uploadDir(path.resolve(__dirname, 'dist'));
  38. q.start(() => {
  39. callback();
  40. });
  41. });
  42. }
  43. }
  44. module.exports = UploadCDNPlugin;