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 _require = require('child_process'); 17const exec = _require.exec; 18const _path = require('path'); 19const snapshot = _path.join(__dirname, '..', '..', 'bin', 'jerry-snapshot'); 20/** 21 * Convert Javascript file to snapshot. 22 */ 23class SnapshotPlugin { 24 /** 25 * constructor of the SnapshotPlugin class. 26 * @param {String} options The object of build folder. 27 */ 28 constructor(options) { 29 this.options = options; 30 } 31 /** 32 * Find all javascript file paths in the directory. 33 * @param {Object} assets the object of javascript file path. 34 * @param {String} buildPath The path of build folder. 35 * @return {Array} Image path array. 36 */ 37 getDir(assets, buildPath) { 38 const pathArray = []; 39 Object.keys(assets).map((item) => { 40 if (/.js$/.test(item)) { 41 pathArray.push(_path.join(buildPath, item)); 42 } 43 }); 44 return pathArray; 45 }; 46 /** 47 * Convert javascript file asynchronously. If an error occurs, print an error message. 48 * @param {Object} compiler API specification, all configuration information of Webpack environment. 49 */ 50 apply(compiler) { 51 const buildPath = this.options.build; 52 compiler.hooks.done.tap('snapshot coverter', (stats) => { 53 const pathArray = this.getDir(stats.compilation.assets, buildPath); 54 pathArray.forEach((element) => { 55 const bcPath = element.replace('.js', '.bc'); 56 const fileName = _path.basename(element); 57 exec(`"${snapshot}" generate -o "${bcPath}" "${element}"`, (error) => { 58 if (error) { 59 console.error('\u001b[31m', `Failed to convert the ${fileName} file to a snapshot.`, '\u001b[39m'); 60 } 61 }); 62 }); 63 }); 64 } 65} 66module.exports = SnapshotPlugin; 67