Giter VIP home page Giter VIP logo

rollup-plugin-critical's Introduction

Build Coverage Badge Scrutinizer Code Quality Code Coverage Build Status

rollup-plugin-critical

Vite.js & Rollup plugin for generating critical CSS that uses the critical generator under the hood.

Install

npm i -D rollup-plugin-critical

Usage

// rollup.config.js

import PluginCritical from 'rollup-plugin-critical';

export default {
  input: 'index.js',
  output: {
    dir: 'dist',
    format: 'es',
  },
  plugins: [
    PluginCritical({
        criticalUrl: 'https://nystudio107.com/',
        criticalBase: './',
        criticalPages: [
            { uri: '', template: 'index' },
            { uri: 'about', template: 'about/index' },
        ],
        criticalConfig: {
        },
    }),
  ],
}

Options

criticalUrl: string

The base URL to use in combination with the criticalPages uris to determine the URLs to scrape for Critical CSS.

This can also be a file system path. This is combined with criticalPages.uri (see below) to determine pages to scrap for critical CSS.

Determines the criticalConfig.src property (see below)

criticalBase: string

The base file system path to where the generated Critical CSS file should be saved.

This is combined with criticalPages.template (see below) with _critical.min.css appended to it to determine the saved critical CSS file name.

Determines the criticalConfig.target property (see below)

criticalPages: array of objects

An array objects that contain the page uris that are combined with the criticalUrl to determine the URLs to scrape for Critical CSS.

The resulting files are named with the template path, and saved to the criticalBase directory

criticalConfig: object

This is the full config for critical that is passed through to the critical package.

You may optionally override any properties you like here. The default values passed in are:

const defaultCriticalConfig: Partial<CriticalConfig> = {
    inline: false,
    extract: false,
    width: 1200,
    height: 1200,
    penthouse: {
        blockJSRequests: false
    }
};

The following critical config properties are set dynamically by rollup-plugin-critical, but can be overridden via criticalConfig:

  • css - set to the css files that are generated in the Rollup build
  • base - property is set to criticalBase
  • src - derived from criticalUrl and criticalPages.uri
  • target - derived from criticalPages.template with _critical.min.css appended to it. If the inline option is set to true, the suffix .html is appended instead.

License

MIT © nystudio107

rollup-plugin-critical's People

Contributors

khalwat avatar matthiasott avatar peschee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rollup-plugin-critical's Issues

Warning: Missing base path. Consider 'base' option.

Question

Getting the following error when running npm run build:

Warning: Missing base path. Consider 'base' option. 

My config:

    critical({
      criticalUrl: 'http://web',
      criticalBase: './web/dist/criticalcss/',
      criticalPages: [
        { uri: '/', template: 'index' },
      ],
    }),

web is one of my service in my Docker-based setup.

Full output:

> [email protected] build /app
> vite build

postcss-discard: postcss.plugin was deprecated. Migration guide:
https://evilmartians.com/chronicles/postcss-8-plugin-migration
vite v2.3.7 building for production...
transforming (14) src/vue/Confetti.vue[vite:css] /app/src/css/utils/typography.pcss is empty
1  |  @import 'tailwindcss/base';
2  |  @import 'tailwindcss/components';
   |   ^
3  |  @import 'tailwindcss/utilities';
4  |  
[vite:css] /app/src/css/utils/vendor.pcss is empty
2  |  @import 'tailwindcss/components';
3  |  @import 'tailwindcss/utilities';
4  |  
   |   ^
5  |  @import 'utils/base.pcss';
6  |  @import 'components/base.pcss';
✓ 27 modules transformed.
rendering chunks (1)...Sourcemap is likely to be incorrect: a plugin (vite:css-post) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
Sourcemap is likely to be incorrect: a plugin (vite:import-analysis) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
rendering chunks (3)...Sourcemap is likely to be incorrect: a plugin (vite:define) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
Sourcemap is likely to be incorrect: a plugin (vite:define) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
Sourcemap is likely to be incorrect: a plugin (vite:define) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
web/dist/assets/lazysizes-legacy.f22f6e95.js   7.38kb / brotli: 3.05kb
web/dist/assets/lazysizes-legacy.f22f6e95.js.map 22.53kb
web/dist/assets/app-legacy.5f35c5f0.js         22.24kb / brotli: 4.91kb
web/dist/assets/app-legacy.5f35c5f0.js.map     0.10kb
web/dist/assets/vendor-legacy.bff03df2.js      22.88kb / brotli: 7.92kb
web/dist/assets/vendor-legacy.bff03df2.js.map  0.10kb
web/dist/assets/polyfills-legacy.549bb6d1.js   41.76kb / brotli: 14.76kb
rendering chunks (1)...Sourcemap is likely to be incorrect: a plugin (vite:import-analysis) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
rendering chunks (3)...Sourcemap is likely to be incorrect: a plugin (vite:define) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
Sourcemap is likely to be incorrect: a plugin (vite:define) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
Sourcemap is likely to be incorrect: a plugin (vite:define) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help
Generating critical CSS from http://web/ to index_critical.min.css
web/dist/assets/WorkSans-Regular.ec25aa37.woff2      69.74kb
web/dist/assets/WorkSans-Italic.abb054a7.woff2       64.42kb
web/dist/assets/WorkSans-Bold.a616b751.woff2         74.10kb
web/dist/assets/WorkSans-BoldItalic.3afecc5a.woff2   68.47kb
web/dist/assets/WorkSans-Black.138beb40.woff2        68.54kb
web/dist/assets/FiraCode-Regular.105c876c.woff2      100.75kb
web/dist/assets/FiraCode-Bold.72e84e14.woff2         104.87kb
web/dist/assets/WorkSans-Italic.fe920528.woff        90.39kb
web/dist/assets/WorkSans-BoldItalic.8fa25a73.woff    95.96kb
web/dist/assets/WorkSans-Black.17ea169f.woff         92.05kb
web/dist/assets/WorkSans-Regular.6f8cccb6.woff       96.48kb
web/dist/assets/WorkSans-Bold.bddfac33.woff          102.63kb
web/dist/assets/FiraCode-Regular.33b9f771.woff       131.13kb
web/dist/assets/FiraCode-Bold.78408fee.woff          136.86kb
web/dist/manifest.json                               2.36kb
web/dist/assets/app.70bede6d.js                      2.00kb / brotli: 0.90kb
web/dist/assets/app.70bede6d.js.map                  0.09kb
web/dist/assets/lazysizes.6959aafd.js                7.30kb / brotli: 3.03kb
web/dist/assets/lazysizes.6959aafd.js.map            33.43kb
web/dist/assets/app.97a6b99f.css                     21.13kb / brotli: 4.39kb
web/dist/assets/vendor.323c439a.js                   22.81kb / brotli: 7.88kb
web/dist/assets/vendor.323c439a.js.map               23.83kb
Warning: Missing base path. Consider 'base' option. https://goo.gl/PwvFVb 

Additional context

Did almost every changes (except for cms/templates/_boilerplate/_partials/critical-css.twig) found here: nystudio107/craft@487ad1f

Adding base option to critical itself or to criticalConfig did not help. The criticalCSS files are generated fine, though.

Npm deprecated alert on install

NPM message on install:

npm` WARN deprecated [email protected]: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility
npm WARN deprecated [email protected]: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated [email protected]: Version no longer supported. Upgrade to @latest
npm WARN deprecated [email protected]: This SVGO version is no longer supported. Upgrade to v2.x.x.

added 392 packages, and audited 559 packages in 15s

126 packages are looking for funding
  run `npm fund` for details

8 high severity vulnerabilities

Some issues need review, and may require choosing
a different dependency.

Node version: 18.7
ViteJS: 3.1
Vue: 3.2

Ability to use an array for criticalUrl

Would it be possible to have the criticalUrl property accept an array of URL's that calls critical.generate() multiple times and have the resulting files prefixed with the second level domain of the URL? This way we can use it together with multi-site in Craft for example.

Elaborate README Usage

Question

I didn't find in the readme a clear statement about what the plugin does (Does it only generate a CSS file? Or it incorporates the generated styles?). I think it would fit in the "Usage" section of Readme.

From trying it out, the only thing I saw it does is that it generates index_critical.min.css. So I assume the plugin doesn't do the next step which is to inline it in my index.html and make the original index.css a non-render-blocking request.

So I think the "Usage" section of Readme should be extended with something like this:

After you've set up the plugin as above, run your build and it generates index_critical.min.css.

You should include index_critical.min.css in your index.html which can be done with the following code snippet:
[ SNIPPET HERE (I have no clue how to do this) ]

You also need to make your original CSS files to be deferred which can be done with the following code snippet:
[ SNIPPET HERE (I have no clue how to do this) ]

Additional context

I didn't use https://github.com/addyosmani/critical before so I don't know how it's expected to work, I only know its goal based on reading https://developer.chrome.com/docs/lighthouse/performance/render-blocking-resources/. I would expect that many people will be in a similar situation to me, which is why I spent my time writing this issue instead of trying to google for how to do it myself.

I'm trying to use this with Vite.

Require error

Describe the bug

In a Craft & Vite project after following the docs and including the standard setup in the vite.config.js plugins section, following error keeps showing after running the commands for serving or building:

Error [ERR_REQUIRE_ESM]: require() of ES Module /XXX/XXX/node_modules/critical/index.js from /XXX/XXX/node_modules/rollup-plugin-critical/dist/index.js not supported.
Instead change the require of /XXX/XXX/node_modules/critical/index.js in /XXX/XXX/node_modules/rollup-plugin-critical/dist/index.js to a dynamic import() which is available in all CommonJS modules.

To reproduce

Steps to reproduce the behaviour:

  1. A Craft CMS setup with vite plugin installed
  2. Add this plugin
  3. Run "vite" or "vite build"
  4. Error in console

Expected behaviour

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Versions

  • Plugin version: 1.0.10
  • Craft version: 4.3.4

Specifying source CSS files is not working

Describe the bug

We're running a project with three different CSS stylings. This is why just generating Critical CSS without specifying CSS source files leads to wrong styling. However, when specifying a CSS source file, the Critical CSS files get created but are empty.

This is the code we're using:

    critical({
      criticalUrl: 'https://www.karriere.at',
      criticalBase: path.resolve('./templates/b2c/'),
      criticalPages: [
        { uri: '/agb', template: 'entry/pagesB2C/cpDefault' },
        { uri: '/blog', template: 'entry/homeBlog/homeBlog' },
        { uri: '/c/a/entscheidung', template: 'entry/blog/default' },
        { uri: '/ueber-uns', template: 'entry/pagesB2C/lpDefault' },
      ],
      criticalConfig: {
        width: 1680,
        height: 1200,
        css: [
         './assets/css/app.css',
        ],
        ignore: {
          rule: [/o-footer/],
        },
        rebase: asset => (asset.url.includes('https://content.karriere.at') || asset.url.includes('https://kcdn.at')) ? `${asset.url}` : `https://content.karriere.at${asset.url}`,
      },

To reproduce

Steps to reproduce the behaviour:
Create Critical CSS with above code. If the css config is set, empty Critical CSS files are created. If the css config is not set, wrong Critical CSS files are created.

Expected behaviour

Critical CSS files are generated and have the correct content.

Versions

  • Plugin version: 1.0.12
  • Craft version: 4.5.5

postcss-discard: postcss.plugin was deprecated.

Describe the bug

I use your great vite buildchain for craft. if i want to "make build" i got this error:
postcss-discard: postcss.plugin was deprecated. Migration guide: vite_1 | https://evilmartians.com/chronicles/postcss-8-plugin-migration

Expected behaviour

I think it has something to do with this plugin an the critical version? maybe it should use critical version 4?

Versions

  • Plugin version: newest

Critical + Penthouse passdown HTML issue

Describe the bug

I was trying to generate critical CSS and I was wondering why only some of my CSS variables were output and no selector at all. The issue was that critical loads the HTML incorrectly through vinyl by getting the HTML document and passing it down as a string to Penthouse. With a server app or SSR, it wouldn't be an issue, but with an SPA with Vue, this seems to prevent Penthouse to execute the scripts and no vu component gets rendered or picked up.

I have tested to make sure that Penthouse does generate the correct HTML and loads the right page and it seems to be okay. By flagging all the debugs inside rollup-plugin-critical, critical and penthouse, I've managed to see that the HTML gets fetched by critical first and passed down instead of letting penthouse load it. 🤔 I wonder if there's a reason for that.

To reproduce

Steps to reproduce the behaviour:

  1. Use the recommended settings from rollup-plugin-critical
  2. Generate a Vue app with vite
  3. Critical CSS only contains general html, body etc. styles and CSS variables

Expected behaviour

Critical CSS should be generated according to the actual HTML generated in the page.

Versions

  • Plugin version: 1.0.9
  • Craft version: 4.3

Vite build error: TypeError: PluginCritical is not a function

Describe the bug

Cannot build Vite project when using this plugin in plugins section in vite.config.ts. It says TypeError: PluginCritical is not a function. What am I doing wrong? I tried rollup.config.js, but it looks like Vite is ignoring that file.

Steps to reproduce

  • Install plugin
  • Import plugin in vite.config.ts with import PluginCritical from 'rollup-plugin-critical'
  • use plugin in config
/// <reference types="vite/client" />
import { defineConfig, loadEnv, splitVendorChunkPlugin } from 'vite'
import react from '@vitejs/plugin-react-swc'
import svgr from 'vite-plugin-svgr'
import eslintPlugin from 'vite-plugin-eslint'
import { sentryVitePlugin } from '@sentry/vite-plugin'
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'
import VitePluginInjectPreload from 'vite-plugin-inject-preload'
import PluginCritical from 'rollup-plugin-critical'


// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {
    build: {
      // required for sentry: tells vite to create source maps
      sourcemap: true,
      // cssCodeSplit: true,
    },
    server: {
      port: 3000,
      host: true,
    },
    plugins: [
      react(),
      svgr(),
      eslintPlugin(),
      sentryVitePlugin({
        url: env.VITE_SENTRY_URL,
        authToken: env.VITE_SENTRY_AUTH_TOKEN,
        org: env.VITE_SENTRY_ORG,
        project: env.VITE_SENTRY_PROJECT,
        release: {
          create: !!env.SENTRY_DEPLOY_ENV,
          deploy: {
            env: env.SENTRY_DEPLOY_ENV || 'Not specified',
          },
          setCommits: {
            auto: true,
            ignoreMissing: true,
          },
        },
        // telemetry: false,
        // debug: true,
      }),
      visualizer({
        template: 'treemap', // or sunburst
        // open: true,
        gzipSize: true,
        brotliSize: true,
        filename: 'analyse.html', // will be saved in project's root
      }),
      splitVendorChunkPlugin(),
      viteCompression(),
      ViteImageOptimizer(),
      VitePluginInjectPreload({
        files: [
          {
            match: /hero-[a-zA-Z0-9]*.webp$/,
          },
        ],
      }),
      PluginCritical({
        criticalUrl: '',
        criticalBase: './',
        criticalPages: [{ uri: '', template: 'index' }],
        criticalConfig: {},
      }),
    ],
  }
})

Screenshots

obrazek

Versions

  • Plugin version: 1.0.12
  • Vite version: 4.3.9

Wrong Critical CSS generated

Describe the bug

We have the Rollup Critical CSS plugin in our Vite project, and the CSS files get generated by the plugin as they should. However, they contain a rather weird Critical CSS, which still leads to Flashes of Unstyled Content. For example, a run on https://www.karriere.at/lp/faqs leads to the following Critical CSS (all of our URLs generate this Critical CSS code):

:root{--swiper-theme-color:#007aff}:root{--swiper-navigation-size:44px}*,:after,:before{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--c-gray-200))}:after,:before{--tw-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:OpenSans,Helvetica,Arial,sans-serif}body{margin:0;line-height:inherit}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}:root{--c-black:0 0 0;--c-white:255 255 255;--c-gray-50:245 247 247;--c-gray-100:237 239 241;--c-gray-200:227 230 233;--c-gray-300:201 205 212;--c-gray-400:162 170 182;--c-gray-500:124 135 151;--c-gray-600:89 102 123;--c-gray-700:67 82 105;--c-gray-800:46 61 86;--c-gray-900:20 37 66;--c-primary-50:244 251 240;--c-primary-100:233 247 222;--c-primary-200:218 239 192;--c-primary-300:198 230 159;--c-primary-400:180 221 127;--c-primary-500:164 213 96;--c-primary-600:139 199 42;--c-primary-700:97 159 0;--c-primary-800:55 120 0;--c-primary-900:13 83 0;--c-secondary-50:230 238 250;--c-secondary-100:205 221 245;--c-secondary-200:179 205 240;--c-secondary-300:129 171 230;--c-secondary-400:104 154 225;--c-secondary-500:53 121 215;--c-secondary-600:3 87 205;--c-secondary-700:2 70 164;--c-secondary-800:2 52 123;--c-secondary-900:20 37 66;--c-tertiary-50:250 238 237;--c-tertiary-100:247 224 222;--c-tertiary-200:240 200 196;--c-tertiary-300:232 172 166;--c-tertiary-400:225 144 137;--c-tertiary-500:218 117 108;--c-tertiary-600:205 70 58;--c-tertiary-700:166 32 30;--c-tertiary-800:117 0 0;--c-tertiary-900:82 0 0}html{scroll-behavior:smooth}body{--tw-bg-opacity:1;background-color:rgb(var(--c-white) / var(--tw-bg-opacity));font-family:OpenSans,Helvetica,Arial,sans-serif;font-size:clamp(1rem,calc(1rem + 0*(100vw - 20rem)),1rem);line-height:1.5;--tw-numeric-figure:lining-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction);--tw-text-opacity:1;color:rgb(var(--c-gray-900) / var(--tw-text-opacity));-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}*,:after,:before{--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }body{font-size:1rem;line-height:1.5;letter-spacing:-.1px;color:#142542}::-webkit-input-placeholder{color:#c9cdd4}::-moz-placeholder{color:#c9cdd4}:-ms-input-placeholder{color:#c9cdd4}*{outline-offset:.125rem}html{-webkit-box-sizing:border-box;box-sizing:border-box}*,:after,:before{-webkit-box-sizing:border-box;box-sizing:border-box}@font-face{font-weight:400;font-style:normal;font-family:Open Sans;font-display:swap;src:url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-regular.woff2) format("woff2"),url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-regular.woff) format("woff")}@font-face{font-weight:400;font-style:italic;font-family:Open Sans;font-display:swap;src:url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-italic.woff2) format("woff2"),url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-italic.woff) format("woff")}@font-face{font-weight:700;font-style:normal;font-family:Open Sans;font-display:swap;src:url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-600.woff2) format("woff2"),url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-600.woff) format("woff")}@font-face{font-weight:700;font-style:italic;font-family:Open Sans;font-display:swap;src:url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-600italic.woff2) format("woff2"),url(https://kcdn.at/assets/fonts/open-sans-v27-latin-ext_latin-600italic.woff) format("woff")}@font-face{font-family:Open Sans-fallback;size-adjust:105.44%;ascent-override:103%;src:local("Arial")}html{-webkit-text-size-adjust:100%;-moz-text-size-adjust:100%;-ms-text-size-adjust:100%;text-size-adjust:100%}body,html{margin:0;padding:0;border:0;vertical-align:baseline;font:inherit;font-size:100%}html{font-family:Open Sans,Open Sans-fallback,Arial,sans-serif;font-variant-numeric:lining-nums}body{-webkit-text-size-adjust:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}::-ms-clear{display:none}html{font-size:100%;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;scroll-behavior:smooth}body{font-size:1rem;line-height:1.5;font-family:OpenSans,Arial,sans-serif;font-weight:400;font-variant-numeric:lining-nums;letter-spacing:-.1px;color:#142542;background:#fff}

What are we doing wrong that the Critical CSS is so general (and the same for all URLs)?

To reproduce

Steps to reproduce the behaviour:

  1. Generate Critical CSS

Expected behaviour

The correct Critical CSS is produced.

Versions

  • Plugin version: 1.0.8
  • Craft version: 3.7.56

How to inline CSS?

Is your feature request related to a problem? Please describe.

I want the CSS to be included in the HTML inline but inline: true does not work with Vite.

Describe the solution you would like

A clear and concise description of what you would like to have happen.

Describe alternatives you have considered

A clear and concise description of any alternative solutions or features you have considered.

Additional context

import vue from "@vitejs/plugin-vue"
import path from "path"
import critical from "rollup-plugin-critical"
import { defineConfig } from "vite"
import { chunkSplitPlugin } from "vite-plugin-chunk-split"
import { ViteCspPlugin } from "vite-plugin-csp"
import { createHtmlPlugin } from "vite-plugin-html"
import viteImagemin from "vite-plugin-imagemin"

import { version } from "./package.json"

export default defineConfig({
  plugins: [
    vue(),
    viteImagemin(),
    chunkSplitPlugin({
      customSplitting: {
        fortawesome: [/@fortawesome\/.*/],
        fontsource: [/@fontsource\/.*/],
      },
    }),
    ViteCspPlugin({
      onDev: "full",
    }),
    createHtmlPlugin({
      minify: process.env.NODE_ENV === "production",
    }),
    critical({
      criticalUrl: "xxxxxxx",
      criticalBase: "dist",
      criticalPages: [{ uri: "", template: "index" }],
      criticalConfig: {
        strict: true,
        inline: true,
      },
    }),
  ],
  define: {
    __VERSION__: JSON.stringify(version),
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
})

Results Generated Unrelated to URL

Question

I am highly confused about the results I am seeing. I've tried multiple different criticalUrl values. I've even used the exact example config from the docs. No matter what I put in, I get this CSS generated:

@charset "UTF-8";@import url(https://use.typekit.net/fbe6xqa.css);@font-face{font-family:AvenirNextVariable;src:url(/assets/fonts/AvenirNextVariableRoman.woff) format("woff-variations"),url(/assets/fonts/AvenirNextVariableRoman.woff2) format("woff2-variations");font-weight:400 900;font-stretch:75% 100%;font-style:normal;font-display:swap}@font-face{font-family:AvenirNextVariable;src:url(/assets/fonts/AvenirNextVariableItalic.woff) format("woff-variations"),url(/assets/fonts/AvenirNextVariableItalic.woff2) format("woff2-variations");font-weight:400 900;font-stretch:75% 100%;font-style:italic;font-display:swap}

Additional context

  • Running locally.

  • That typekit, and those type styles, are from my local project.

  • I see the following logs:

    Generating critical CSS from https://nystudio107.com/ to index_critical.min.css
    Generating critical CSS from https://nystudio107.com/about to about/index_critical.min.css
    

Support for uri array with one template

Is your feature request related to a problem? Please describe.

For a very large project with over 2k pages and 20+ layouts, we use critical css at layout level. Layout 1, for example, is used for 500 pages. If layout 1 looks different for 100 pages due to e.g. a different hero variant, the critical css will be generated correctly for either 100 or 400 pages.

Describe the solution you would like

It would be cool if something like this were possible:

 criticalPages: [
        { uri: ['/slug1', '/slug2'], template: '_layouts/default_teasers' },
      ],

And the CSS classes could then be merged into a single stylesheet. The problem would then be a possibly larger file that would have to be loaded, but I think that would be within reason if it is not exaggerated :D

Describe alternatives you have considered

Alternatively, that would also be fine:

      criticalPages: [
        { uri: '/slug1', template: '_layouts/default_teasers' },
        { uri: '/slug2', template: '_layouts/default_teasers' },
      ],

Additional context

I know that normally the Critical Css should be generated at page level, but this is difficult to achieve and maintain for large projects. A workaround would also be to create Critical CSS at 90% layout level and in special cases where it does not work well to go back to page level

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.