1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16const _path = require('path'); 17const fs = require('fs'); 18const registerRequireContextHook = require('babel-plugin-require-context-hook/register'); 19const { REGEXP_PNG } = require('./lite-enum'); 20const iconPath = process.env.iconPath || ''; 21const img2bin = require('./lite-image2bin'); 22 23registerRequireContextHook(); 24/** 25 * Convert picture to bin format. 26 */ 27class ImageCoverterPlugin { 28 /** 29 * constructor of the ImageCoverterPlugin class. 30 * @param {String} options The object of build folder. 31 */ 32 constructor(options) { 33 this.options = options; 34 } 35 /** 36 * Find all image paths in png、jpg、bmp、jpeg format in the directory. 37 * @param {String} buildPath The path of build folder. 38 * @return {Array} Image path array. 39 */ 40 getDir(buildPath) { 41 const pngPath = global.__requireContext('', buildPath, true, REGEXP_PNG); 42 const pathArray = pngPath.keys().map((element) => { 43 return _path.join(buildPath, element); 44 }); 45 return pathArray; 46 } 47 /** 48 * Convert image format asynchronously, return code 0 successfully, otherwise return 1. 49 * @param {Object} compiler API specification, all configuration information of Webpack environment. 50 */ 51 apply(compiler) { 52 const buildPath = this.options.build; 53 const getDir = this.getDir; 54 compiler.hooks.done.tap('image coverter', function(compilation, callback) { 55 const pathArray = getDir(buildPath); 56 const writeResult = (content) => { 57 fs.writeFile(_path.resolve(buildPath, 'image_convert_result.txt'), content, (err) => { 58 if (err) { 59 return console.error(err); 60 } 61 }); 62 }; 63 const totalImageCount = pathArray.length; 64 if (totalImageCount > 0) { 65 const promiseArray = pathArray.map((path) => { 66 return img2bin(path); 67 }); 68 Promise.all(promiseArray).then(() => { 69 writeResult('{exitCode:0}'); 70 }).catch(() => { 71 writeResult('{exitCode:1}'); 72 }); 73 } else { 74 writeResult('{exitCode:0}'); 75 } 76 if (iconPath !== '') { 77 const iconArray = getDir(iconPath); 78 iconArray.forEach((path) => { 79 img2bin(path); 80 }); 81 } 82 }); 83 } 84} 85module.exports = ImageCoverterPlugin; 86