UNPKG

@iamota/iamota-webpack

Version:

Helper tools for Webpack for iamota Framework (WordPress and Shopify)

160 lines (146 loc) 3.99 kB
// ---------------------------------------------------------------------------- // Webpack Image Config // ---------------------------------------------------------------------------- // // Webpack configuration to process images // // ---------------------------------------------------------------------------- /** * Load Dependencies */ const { merge } = require('webpack-merge'); const path = require('path'); const svgToMiniDataURI = require('mini-svg-data-uri'); /** * Initialize Config */ let config = {}; exports.init = function(config) { this.config = config; return this; }; /** * Optimize images */ exports.optimize = ({ options = { mozjpeg: { progressive: true, quality: 65 }, optipng: { enabled: true, }, pngquant: { quality: [0.65, 0.90], speed: 4 }, gifsicle: { interlaced: false, }, } } = {}) => ({ module: { rules: [ { // Apply rule for GIF, PNG, JPG, SVG, or ICO files test: /\.(gif|png|jpe?g|svg|ico)$/i, use: [ { // This transform and optimizes image files loader: 'image-webpack-loader', options: options, }, ] }, ], } }); /** * Convert embed small assets, extract others to the images folder */ exports.inlineOrExtract = ({ maxInlineSize = (8 * 1024), outputFilename = 'images/[name][ext]', } = {}) => merge([ this.inlineOrExtractImages({ maxInlineSize: maxInlineSize, outputFilename: outputFilename, }), this.inlineOrExtractSVGs({ maxInlineSize: maxInlineSize, outputFilename: outputFilename, }), ]); /** * Convert small image assets into inline strings, extract others to the images folder */ exports.inlineOrExtractImages = ({ maxInlineSize = (8 * 1024), outputFilename = 'images/[name][ext]', } = {}) => ({ module: { rules: [ { // Inlines small image assets as a Base64 string test: /\.(png|jpe?g|gif)$/i, type: 'asset', generator: { filename: outputFilename, }, parser: { dataUrlCondition: { maxSize: maxInlineSize } }, }, ], } }); /** * Convert small SVG assets into inline strings, extract others to the images folder */ exports.inlineOrExtractSVGs = ({ maxInlineSize = (8 * 1024), sourcePath = path.resolve(this.config.sourcePath, 'assets/images'), outputFilename = 'images/[name][ext]', } = {}) => ({ module: { rules: [ { // SVG can be compressed into a more compact output, avoiding base64 test: /\.svg$/, include: [sourcePath], type: 'asset', generator: { filename: outputFilename, dataUrl: (content) => svgToMiniDataURI(content.toString()), }, parser: { dataUrlCondition: { maxSize: maxInlineSize } }, }, ], } }); /** * Extract images to the images folder */ exports.extract = ({ outputFilename = 'images/[name][ext]', } = {}) => ({ module: { rules: [ { // Apply rule for GIF, PNG, JPG, SVG, or ICO files test: /\.(gif|png|jpe?g|svg|ico)$/i, type: 'asset/resource', generator: { filename: outputFilename, } }, ], } });