Forked from bayareawebpro/critical-css-laravel-mix.js
Created
September 18, 2018 04:52
-
-
Save puncoz/64a91e74f044ec1bdbc4e6ae1522f084 to your computer and use it in GitHub Desktop.
Generate Critical CSS Paths with Laravel Mix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let mix = require('laravel-mix'); | |
let httpRequest = require('request') | |
let criticalCSS = require('critical') | |
//Run your asset compilation commands... | |
//Then we will generate critical css... | |
mix.then(()=>{ | |
console.log("Build Post-Processing...") | |
const criticalRoutes = [ | |
{ | |
url: 'http://laravel.local/', | |
save: 'critical.css' | |
}, | |
] | |
criticalRoutes.forEach((route) => { | |
/** | |
* Fetch Page Urls from Local Server | |
* @docs https://www.npmjs.com/package/request | |
*/ | |
console.log("Fetching Critical CSS Paths...", route.url) | |
httpRequest(route.url, (error, response, body) => { | |
/** Stop on Empty Body String */ | |
if(!body){ | |
throw new Error("Response Body Empty!") | |
} | |
/** Stop on HTTP Error */ | |
if(error){ | |
throw new Error(error) | |
} | |
/** | |
* Generate Critical CSS Path | |
* @docs https://github.com/addyosmani/critical | |
*/ | |
console.log("Processing Critical CSS Paths...", route.url) | |
criticalCSS.generate({ | |
inline: false, //Must be disabled. | |
base: path.resolve(__dirname, '/'), //Project base path | |
html: body, //HTML string fetched | |
src: '', //Must be empty. | |
css: ['resources/assets/dist/theme.css'], | |
width: 1300, //Browser width | |
height: 900, //Browser height | |
dest: 'resources/assets/dist/' + route.save, //Output file path. | |
minify: true, //Minify output. | |
extract: false, //Must be disabled. | |
timeout: (20 * 1000), //Timeout in seconds | |
inlineImages: false, //Inline small images | |
assetPaths: [ | |
'public/images',//Inline asset paths. | |
], | |
ignore: ['@font-face',/url\(/], //ignore rules. | |
ignoreOptions: {} | |
}) | |
.then(function (output) { | |
console.log("Critical CSS Generated Successfully!", route.url) | |
}) | |
.error(function (err) { | |
console.log("Critical CSS Generator Error...", route.url, err) | |
}); | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment