|
| 1 | +import { minify } from 'minify' |
| 2 | +import fs from 'fs' |
| 3 | +import os from 'os' |
| 4 | +import path from 'path' |
| 5 | +import { getLogger, isDirectory, pathWithTrailingSeparator } from '../lib/utils.mjs' |
| 6 | + |
| 7 | +const supportedExtensions = ['.js', '.html', '.css'] |
| 8 | + |
| 9 | +export async function minifyFile (inputFile, addSuffix, outputPath) { |
| 10 | + // Calculate output path |
| 11 | + const fileSeparatorIndex = inputFile.lastIndexOf(path.sep) |
| 12 | + if (outputPath) { |
| 13 | + getLogger().debug('Output path is specified') |
| 14 | + |
| 15 | + // Create output folder if it doesn't exist |
| 16 | + if (!fs.existsSync(outputPath)) { |
| 17 | + fs.mkdirSync(outputPath, { recursive: true }) |
| 18 | + } |
| 19 | + } else { |
| 20 | + // Can be -1 if input file is in the working folder |
| 21 | + if (fileSeparatorIndex !== -1) { |
| 22 | + outputPath = inputFile.substring(0, fileSeparatorIndex) |
| 23 | + } else { |
| 24 | + outputPath = '' |
| 25 | + } |
| 26 | + } |
| 27 | + getLogger().debug('Output path: ', outputPath) |
| 28 | + |
| 29 | + // Extract input file name and extension |
| 30 | + const inputFileExtension = path.extname(inputFile) |
| 31 | + const inputFileName = path.basename(inputFile, inputFileExtension) |
| 32 | + |
| 33 | + // Calculate complete output file name |
| 34 | + const outputFileName = pathWithTrailingSeparator(outputPath) + inputFileName + (addSuffix ? '.min' : '') + inputFileExtension |
| 35 | + getLogger().debug('Complete output file name: ', outputFileName) |
| 36 | + |
| 37 | + // Minify file and write to output file |
| 38 | + const minifiedContent = await minify(inputFile) |
| 39 | + getLogger().debug(minifiedContent) |
| 40 | + fs.writeFileSync(outputFileName, `${minifiedContent}${os.EOL}`) |
| 41 | + |
| 42 | + getLogger().info('Minified ', inputFile, ' > ', outputFileName) |
| 43 | +} |
| 44 | + |
| 45 | +export function minifyFiles (inputPath, addSuffix, outputPath) { |
| 46 | + if (isDirectory(inputPath)) { |
| 47 | + getLogger().debug('Input path ', inputPath, ' is a directory') |
| 48 | + |
| 49 | + // Loop through all the files in the input path |
| 50 | + fs.readdir(inputPath, function (_, files) { |
| 51 | + files.forEach(function (file, index) { |
| 52 | + minifyFiles(pathWithTrailingSeparator(inputPath) + file, addSuffix, outputPath) |
| 53 | + }) |
| 54 | + }) |
| 55 | + } else { |
| 56 | + getLogger().debug('Input path ', inputPath, ' is a file') |
| 57 | + |
| 58 | + if (supportedExtensions.includes(path.extname(inputPath))) { |
| 59 | + minifyFile(inputPath, addSuffix, outputPath) |
| 60 | + } else { |
| 61 | + getLogger().debug('Skipping file ', inputPath, ' with unsupported extension') |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments