UNPKG

@gravityforms/gulp-tasks

Version:
58 lines (54 loc) 2.2 kB
/** * Parses an array of cache group definitions and returns an object containing the parsed cache groups. * For use in a webpack config in the optimizations.splitChunks entry. * Allows you to control the shape of the webpack vendor chunks for optimal delivery. * Compare outputs with the webpack reports at root of project in reports dir to see effects when running release. * * @param {Array} cacheGroupDefinitions - An array of cache group definitions. * * @returns {Object} - An object containing the parsed cache groups. * @example * const cacheGroupParser = require( '@gravityforms/gulp-tasks/src/utils/cache-group-parser' ); * * const cacheGroupDefinitions = [ * { name: 'vendor-admin', test: /[\\/]node_modules[\\/]/, priority: -10 }, * { name: 'vendor-react', packages: ['react', 'react-dom'], priority: 20 }, * { name: 'vendor-react-router', packages: ['react-router', 'react-router-dom', '@remix-run'], priority: 30 }, * { name: 'vendor-simplebar', packages: ['simplebar', 'simplebar-react'], priority: 40 }, * { name: 'vendor-immer', packages: ['immer'], priority: 50 }, * { name: 'vendor-react-paginate', packages: ['react-paginate'], priority: 50 }, * { name: 'vendor-components', test: /[\\/]node_modules[\\/]@gravityforms[\\/]components[\\/]/, priority: 70 }, * { name: 'default', minChunks: 2, priority: -20, reuseExistingChunk: true }, * ]; * * const optimization = { * splitChunks: { * cacheGroups: cacheGroupParser( cacheGroupDefinitions ), * }, * }; */ const cacheGroupParser = ( cacheGroupDefinitions ) => cacheGroupDefinitions.reduce( ( acc, { name, test, packages, priority, minChunks, reuseExistingChunk } ) => { if ( packages ) { acc[ name ] = { test: ( module ) => new RegExp( `node_modules[\\\\/](${packages.join('|')})($|[\\\\/])` ).test( module.context ), name, chunks: 'all', priority, }; } else { acc[ name ] = { test, name, chunks: 'all', priority, }; if ( minChunks ) { acc[ name ].minChunks = minChunks; } if ( reuseExistingChunk !== undefined ) { acc[ name ].reuseExistingChunk = reuseExistingChunk; } } return acc; }, {} ); module.exports = cacheGroupParser;