Gulp Critical CSS and Twig Files - css

I'm trying to use this for applying critical css into my twig files.
I've had this working perfectly before but i've updated to gulp 4 and restructured my gulp file(s). i'm trying to also include multiple dimensions.
Any help would be much appreciated.
var critical = require( 'critical' ).stream;
function critical() {
return critical( plugins.path.join( project.paths.base ) )
.pipe( critical.generate({ inline: true, base: project.paths.views, dest: plugins.path.join( project.paths.views, 'html-header.twig' ), src: plugins.path.join( project.paths.build, 'css/style.min.css' ),
dimensions: [{
height: 200,
width: 500
}, {
height: 900,
width: 1200
}] }) )
.pipe( gulp.dest( project.paths.views ) );
}
gulp.task( 'critical-css', critical );
Here is my gulpfile.js
'use strict';
/**
* Project Setup
*
* Setting up variables for project name and directories
*/
/******************************************************************************
| > PLUGINS
******************************************************************************/
global.gulp = require('gulp');
var HubRegistry = require('gulp-hub');
var hub = new HubRegistry(['tasks/{,**/}*.js']);
global.plugins = {
path: require('path'),
rename: require('gulp-rename'),
changed: require('gulp-changed'),
concat: require('gulp-concat'),
browserSync: require('browser-sync'),
sourcemaps: require('gulp-sourcemaps')
};
/******************************************************************************
| > PROJECT VARIABLES
******************************************************************************/
global.project = {
name: 'base',
url: 'localhost:8888/base/',
phpSource: ['**/*.php', 'page-templates/**/*.php', '!library/**/*', '!wpcs/**/*', '!node_modules/**/*', '!vendor/**/*', '!assets/bower_components/**/*', '!**/*-min.css', '!assets/js/vendor/*', '!assets/css/*', '!**/*-min.js', '!assets/js/production.js'],
paths: {
base: __dirname,
build: plugins.path.join( __dirname, 'build' ),
src: plugins.path.join( __dirname, 'src' ),
vendors: plugins.path.join( __dirname, 'vendor' ),
tasks: plugins.path.join( __dirname, 'tasks' ),
views: plugins.path.join( __dirname, 'views' ),
assets: plugins.path.join( __dirname, 'assets' ),
assets: {
sass: plugins.path.join( __dirname, 'src/sass' ),
images: plugins.path.join( __dirname, 'assets/img' ),
js: plugins.path.join( __dirname, 'assets/js' ),
css: plugins.path.join( __dirname, 'assets/css' )
}
}
};
gulp.registry(hub);
gulp.task('images', gulp.series('image-fallback', 'image-optimise', 'image-responsive'));
The critical css needs to go into html-header.twig
<!doctype html>
<!--[if lt IE 7]><html class="no-js ie ie6 lt-ie9 lt-ie8 lt-ie7" {{site.language_attributes}}> <![endif]-->
<!--[if IE 7]><html class="no-js ie ie7 lt-ie9 lt-ie8" {{site.language_attributes}}> <![endif]-->
<!--[if IE 8]><html class="no-js ie ie8 lt-ie9" {{site.language_attributes}}> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" {{site.language_attributes}}> <!--<![endif]-->
<html id="csstyle">
<head>
<meta charset="{{site.charset}}" />
<title>
{% if wp_title %}
{{ wp_title }} - {{ site.name }}
{% else %}
{{ site.name }}
{% endif %}
</title>
<meta name="description" content="{{site.description}}">
<link rel="stylesheet" href="{{site.theme.link}}/style.css" type="text/css" media="screen" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{function('wp_head')}}
I can't post images because of my small reputation.
Here is my file structure:
File Structure
When I run gulp critical-css in the terminal i get this error
[10:47:17] The following tasks did not complete: critical-css
[10:47:17] Did you forget to signal async completion?
I'm using version 0.7.1 of Critical
Thanks Jake.

Looking at the first four lines:
var critical = require( 'critical' ).stream;
function critical() {
return critical( plugins.path.join( project.paths.base ) )
.pipe( critical.generate(
You define a function and a var both named critical. Name you function criticalCss or anything else.
You're using path.join with a single argument. Probably missing something here.
critical.stream can only take an options object, not a path. You want return gulp.src instead of return critical.
critical.generate doesn't return a stream.Transform, so you can't pass it to stream.pipe(). You want critical({}) like in this example.

Related

Why Tailwind Height doesn't work (breakpoints)?

I installed Tailwind CSS and Elements on my Laravel project.
I'm doing the responsive part, but the "height" is not working when I use breakpoints (i.e "md:xxx").
I tried with other things like background color, width or flex, it's working.
<div class="bg-pink-500 md:bg-black h-16 md:h-64"></div>
The only change I made on Tailwind is to set my application color palette.
I see someone having the same issue and talking about a file missing (postcss.config.js).
I have postcss installed (v8.4.6) in my package.
I tried to manually create the file and fill with this (doesn't work) :
postcss.config.js
module.exports = {
plugins: [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]
}
Here is my code :
HTML CSS links
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
{{-- Tailwind Components --}}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght#300;400;500;600;700&display=swap" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tw-elements/dist/css/index.min.css" />
webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]);
mix.sass('resources/scss/style.scss', 'public/css');
tailwind.config.js
const defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
purge: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
'./resources/**/*js'
],
theme: {
extend: {
fontFamily: {
'montserrat': ['Montserrat'],
sans: ['Montserrat'],
serif: ['Montserrat'],
mono: ['Montserrat'],
display: ['Montserrat'],
body: ['Montserrat']
// sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
colors: {
'black1': '#181818',
'black2': '#323232',
'white0': '#F9F9F9',
'white1': '#F1F1F1',
'white2': '#E4E4E4',
'red1': '#8E0000',
'red2': '#BA0000',
'red3': '#D62323'
},
},
},
variants: {
extend: {
opacity: ['disabled']
},
},
plugins: [
require('#tailwindcss/forms')
]
};
Thank you
UPDATE:
The css keeps default settings instead of using my breakpoint settings.
Screenshot of CSS in dev tool
Has you can see on the post's screenshot, the CSS file (index.min.css) coming from Tailwind CDN overwritte app.css, just call Tailwind CDN first:
{{-- Tailwind Components --}}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght#300;400;500;600;700&display=swap" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tw-elements/dist/css/index.min.css" />
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/style.css') }}">
<link rel="stylesheet" href="{{ asset('css/app.css') }}">

Delayed loading of css on page refresh (Webpack)

I have splitted webpack configurations, common, development and production configs. I load also jQuery via webpack. The problem is that, on page refresh, there is short delay for about 200-300ms before css is loaded, so my page is firstly shown without it, and then reloads with css. What could be the problem?
In common, under plugins, I have:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
In development config I have:
{
test: /\.scss$|\.css$/,
use: [
{
loader: "style-loader",
options: {sourceMap: true}
},
{
loader: "css-loader",
options: {sourceMap: true}
},
{
loader: "sass-loader",
options: {sourceMap: true}
}
]
},
and for production mode:
optimization: {
minimizer: [
new UglifyJSPlugin({
sourceMap: true,
uglifyOptions: {
mangle: false,
compress: {
inline: false
}
}
}),
new OptimizeCssAssetsPlugin({
cssProcessor: require('cssnano'),
cssProcessorOptions: {parser: _safe, discardComments: {removeAll: true}},
canPrint: true
})
]
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}
]
}
EDIT
Here is compiled html file:
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta name=viewport content="width=device-width">
<meta http-equiv=X-UA-Compatible content="ie=edge">
<link rel="shortcut icon" href="favicon.png">
</head>
<body>
<div id=app></div>
<script type="text/javascript" src="main.bundle.js?32313079e3d03749d814"></script>
</body>
</html>
Maybe it is too late to answer this question, however, that is not related to Webpack. You have attached your bundle at the end of the page. Therefore before loading the bundle the page content comes up and after that bundles loaded the style. Therefore until it loads the completely there is a little time that takes time for the browser to run the bundle and attach the style. It can be fixed by putting the bundle in the <head> tag. You may need to run your jquery codes inside $(document).ready() function by passing a callback as an argument. Pay attention that it can affect the load time of your page as well.
Another solution can be configuring Webpack to load the styles first and then your js codes.

Vue Firebase Hosting App Built Files Are Incorrect

I am working on a Firestore, Vue project and having an issue with building my project. Running the non-built files on a local server works just fine and after running the build command, the files all appear to be correct. However, after uploading the files to Firebase (or creating a local server using the built files using the firebase serve command), it just shows a blank page. So I inspected the files and the css and js files are the exact same as the HTML file.
I know that this guy had the same issue, Upload to Firebase Hosting not working correctly, but I have gone through every file I feel like may be the culprit and still cannot find where the issue is — although that may just be due to my lack of knowledge in how webpack works. I think it may be some misconfiguration in the vue.config.js file but not sure. I would appreciate any help in getting my project hosted! Thanks!
Here is my file structure:
- dist
- src
- assets
- css
- img
- js
- favicon.ico
- index.html
- public
- index.html
- src
- App.vue
- main.ts
- .firebaserc
- firebase.json
- package.json
- vue.config.js
Compiled index.html
<!DOCTYPE html>
<html lang=en>
<head>
<meta http-equiv=Content-Type content="text/html; charset=UTF-8">
<meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=msapplication-tap-highlight content=no>
<meta name=description content="Steel Tech of the Ozarks designs & manufactures pre-engineered metal buildings, driven by an intentional, no-compromise passion for excellence.">
<meta name=keywords content=steel,building,metal,structural,design,manufacture>
<title>Company Name</title>
<link rel="shortcut icon" href=../src/assets/favicon/favicon.ico>
<meta name=theme-color content=#6e8995>
<link as=style href=/dist/src/assets/css/app.64e0dd85.css rel=preload>
<link as=style href=/dist/src/assets/css/chunk-vendors.9e123139.css rel=preload>
<link as=script href=/dist/src/assets/js/app.00d6273a.js rel=preload>
<link as=script href=/dist/src/assets/js/chunk-vendors.90527da6.js rel=preload>
<link href=/dist/src/assets/css/chunk-vendors.9e123139.css rel=stylesheet>
<link href=/dist/src/assets/css/app.64e0dd85.css rel=stylesheet>
</head>
<body>
<noscript>
<strong>We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id=app>
<script src=/dist/src/assets/js/chunk-vendors.90527da6.js></script>
<script src=/dist/src/assets/js/app.00d6273a.js></script>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="msapplication-tap-highlight" content="no">
<title>Company Name</title>
<link rel="apple-touch-icon" sizes="180x180" href="../src/assets/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="../src/assets/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../src/assets/favicon/favicon-16x16.png">
<link rel="manifest" href="../src/assets/favicon/site.webmanifest">
<link rel="mask-icon" href="../src/assets/favicon/safari-pinned-tab.svg" color="#ff6600">
<link rel="shortcut icon" href="../src/assets/favicon/favicon.ico">
</head>
<body>
<noscript>
<strong>We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<!-- Built files will be auto injected -->
<div id="app"/>
</body>
</html>
App.vue
<template>
<v-app>
<router-view/>
</v-app>
</template>
main.ts
import Vue from 'vue'
import App from './App.vue'
import router from '#/router'
import store from '#/store'
import '#/plugins/vuetify'
Vue.config.productionTip = false
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app')
.firebaserc
{
"projects": {
"default": "schedule-maxx"
}
}
firebase.json
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
vue.config.js
module.exports = {
runtimeCompiler: true,
lintOnSave: true,
productionSourceMap: false,
outputDir: 'dist',
assetsDir: 'src/assets',
baseUrl: process.env.NODE_ENV === 'production' ? '/dist/' : '/',
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: {
'^/api': '/api/v1'
}
}
}
}
}
With regards to your file structure, in particular:
dist
public
index.html
and to the fact that you rewrite to /index.html (cf. firebase.json file)
I think that your firebase.json file should start as follows. (However, since you don't show what's in the dist directory I am not 100% sure!):
{
"hosting": {
"public": "public",
....
}
}
and the static directory generated by webpack should also be deployed under the public directory. It is most probably under the dist directory for the moment.
It looks like I just had my vue.config.js file configured incorrectly. I changed the baseUrl field from '/dist/' to '.' and the file paths in the compiled files were correct.

The exit status code '1' says something went wrong [knp snappy]

I'm working with knp snappy bundle for generate reports from my app. But doesn't work, when I call my controller for generate the pdf throws the next error:
The exit status code '1' says something went wrong:
stderr: "Loading pages (1/6)
[> ] 0%
[======> ] 10%
[=======> ] 12%
Warning: Failed to load file:///gestionresiduospel/web/bundles/usuario/css/bootstrap.css (ignore)
Warning: Failed to load file:///gestionresiduospel/web/bundles/usuario/js/bootstrap.js (ignore)
[============================================================] 100%
Counting pages (2/6)
[============================================================] Object 1 of 1
Resolving links (4/6)
[============================================================] Object 1 of 1
Loading headers and footers (5/6)
Printing pages (6/6)
[> ] Preparing
[============================================================] Page 1 of 1
Done
Exit with code 1 due to network error: ContentNotFoundError
"
stdout: ""
command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" --lowquality "C:\Users\rodrigo\AppData\Local\Temp\knp_snappy5682878973ade7.09664058.html" "C:\Users\rodrigo\AppData\Local\Temp\knp_snappy56828789746968.46649162.pdf".
My controller is this:
public function historicosDetallePdfAction($id)
{
$em = $this->getDoctrine()->getManager();
//gets residuos peligrosos.
$solicitudRetiro= $em->getRepository('SolicitudRetiroBundle:SolicitudRetiro')->find($id);
//gets residuos no peligrosos
$residuosPRetirados = $em->getRepository('SolicitudRetiroBundle:RetiroResiduo')->findResiduos($id);
//retorna los residuos no peligrosos en la solicitud
$residuosNPRetirados = $em->getRepository('SolicitudRetiroBundle:RetiroResiduoNoPeligroso')->findResiduosNoPeligrosos($id);
// view generator
$html = $this->renderView('SolicitudRetiroBundle:Pdf:resumenSolicitudResiduoRetirado.html.twig', array(
'solicitudRetiro' => $solicitudRetiro,
'residuosRetirados' => $residuosPRetirados,
'residuosNoPel' => $residuosNPRetirados ));
// pdf generator
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="historico.pdf"'
)
);
}
I copied my url and run into console[CMD] with wkhtmltopdf.exe. In console my pdf is created but when I see the file only shows my login screen. So I think could be a issue about permission into my controller but I don't know how I pass this.
In other hand, if you know about another pdf generator(from html) that working into symfony this could be help me too.
I'm working under symfony2.7
This mean's that one of the resources in your HTML file can't be loaded by wkhtmltopdf, check in your HTML file if all your resources have an absolute URL like this : http://www.yourserver.com/images/myimage.jpg
If it's not the case try to set it :
{{ app.request.schemeAndHttpHost ~ 'resource relative url' }}
If you are loading assets with assetic in {% stylesheets %} or {% javascript %} or {% image %} you can also do
{{ app.request.schemeAndHttpHost ~ asset_url }}
I had two kind of problems here once:
The first one was because kpn snappy fails when trying to convert a *.js file. So I had to take *.js files in my case.
The second one was because of the path. I had to use the absolute filesystem path. By this, I mean, something like: /home/ubuntu/workspace/bootstrap/css/bootstrap.css this is used in href tag used in *html.twig file that is then transformed to pdf by snappy.
By doing this, I used some twig global variables.
twig:
form:
resources:
- 'MyBundle:Form:fields.html.twig'
- 'MyUploaderBundle:Form:fields.html.twig'
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
pathToWeb: "%kernel.root_dir%/../web"
bootstrapCss: "/home/ubuntu/workspace/MyApp/web/bootstrap/css/bootstrap.css"
mainCss: "/home/ubuntu/workspace/MyApp/web/css/main.css"
layoutCss: "/home/ubuntu/workspace/MyApp/web/css/layout.css"
In twig
<link rel="stylesheet" type="text/css" href="{{ bootstrapCss }}">
<link rel="stylesheet" type="text/css" href="{{ layoutCss }}">
<link rel="stylesheet" type="text/css" href="{{ mainCss }}">
You can use absolute_url() twig function{{ absolute_url(asset('assets/image.jpg')) }}
For me this worked, the error was from html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
{% for path in encore_entry_css_files('app') %}
<link rel="stylesheet" href="{{ absolute_url(path) }}">
{% endfor %}
</head>
This problem never gets old, I encountered this just now and I manage to solve it, here's how.
This problem mostly happens in Windows so this solution is for that.
1. Install this composer dependency wemersonjanuario/wkhtmltopdf-windows
composer require wemersonjanuario/wkhtmltopdf-windows "0.12.2.3"
2. Open your config/snappy.php and use this config.
<?php
return [
'pdf' => [
'enabled' => true,
'binary' => base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltopdf'),
'timeout' => false,
'options' => [],
'env' => [],
],
'image' => [
'enabled' => true,
'binary' => base_path('vendor\wemersonjanuario\wkhtmltoimage-windows\bin\64bit\wkhtmltoimage'),
'timeout' => false,
'options' => [
'enable-local-file-access' => true,
'keep-relative-links' => true,
],
'env' => [],
],
];
3. Make sure the blade file you loading for pdf does not contain external links, like the one below.
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght#0,300;0,400;0,600;0,700;1,300;1,400;1,600;1,700&display=swap" rel="stylesheet">
</head>
4. Make sure you load assets using public_path()
<link href="{{ public_path('css/pdf.css') }}" rel="stylesheet">
<img src="{{ public_path('fancy-image.png') }}">

treegrid example doesn't work

I'm trying to run the treegrid example but it only gives me the grid with no data in it!
this is my default.aspx:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My tree grid</title>
<!-- Ext -->
<link rel="stylesheet" type="text/css" href="ExtJs4/resources/css/ext-all.css" />
<script type="text/javascript" src="ExtJs4/bootstrap.js"></script>
<script type="text/javascript" src="ExtJs4/ext-all.js"></script>
<!-- example code -->
<script type="text/javascript" src="Scripts/treepanel.js"></script>
</head>
<body>
<h1>My tree grid</h1>
<div id="tree-div"> </div>
this is my treepanel.js
Ext.Loader.setConfig({ enabled: true }); //
Ext.Loader.setPath('Ext.ux', '../ux');
Ext.require([
'Ext.tip.QuickTipManager',
'Ext.container.Viewport',
'Ext.layout.*',
'Ext.form.Panel',
'Ext.form.Label',
'Ext.grid.*',
'Ext.data.*',
'Ext.tree.*',
'Ext.selection.*',
'Ext.tab.Panel'
]);
Ext.onReady(function ()
{
Ext.define('Task', {
extend: 'Ext.data.Model',
fields: [
{name: 'task', type: 'string'},
{name: 'user', type: 'string'},
{name: 'duration', type: 'string'}
]
});
var store = Ext.create('Ext.data.TreeStore', {
model: 'Task',
proxy: {
type: 'ajax',
url: 'treegrid.json'////
},
folderSort: true
});
//Ext.ux.tree.TreeGrid is no longer a Ux. You can simply use a tree.TreePanel
var tree = Ext.create('Ext.tree.Panel', {
title: 'Core Team Projects',
width: 500,
height: 300,
renderTo: 'tree-div',
rootVisible:true,
store: store,
autoload:true,
columns: [{xtype: 'treecolumn', text: 'Task', dataIndex: 'task' },{text: 'Assigned To', dataIndex: 'user'}]
});
});
am I doing something wrong here?
I have no error msg from my firebug...so why isn't it working?
if I can't run an example how am I going to do more..I'm frustrated with this.
not sure, but the "autoLoad: true" is now on the panel, but shouldn't it be on the store?
Install PHP and do the following in IIS:
click on the new site
click on MIME types
right click in open space > Add > File name extension: "json" ... MIME Type: "application/x-javascript"
Adding more details:
http://www.sencha.com/forum/showthread.php?33266-Some-Problem-with-JSON&p=229858&viewfull=1#post229858

Resources