GithubHelp home page GithubHelp logo

playform / inline Goto Github PK

View Code? Open in Web Editor NEW
194.0 2.0 7.0 2.2 MB

🦔 Inline —

Home Page: https://NPMJS.Org/@playform/inline

License: MIT License

TypeScript 95.89% JavaScript 4.11%
astro critters critical-css inline-css playform inline astro-component astro-integration astro-critters astro-inline

inline's Introduction

Astro

Related —


Build
Dependency
Version


Star
Download
🗜️ Compress —

Build
Dependency
Version


Star
Download
🗻 Format —

🦔 Inline —

This Astro integration brings critters to your Astro project.

Critters is a plugin that inlines your app's critical CSS and lazy-loads the rest.

Note

Inline will not inline your requests, only your statically generated build and pre-rendered routes.

Installation

There are two ways to add integrations to your project. Let's try the most convenient option first!

astro add command

Astro includes a CLI tool for adding first party integrations: astro add. This command will:

  1. (Optionally) Install all necessary dependencies and peer dependencies
  2. (Also optionally) Update your astro.config.* file to apply this integration

To install Inline, run the following from your project directory and follow the prompts:

Using NPM:

npx astro add @playform/inline

Using Yarn:

yarn astro add @playform/inline

Using PNPM:

pnpx astro add @playform/inline

Install dependencies manually

First, install the Inline integration like so:

npm install -D -E @playform/inline

Then, apply this integration to your astro.config.* file using the integrations property:

export default {
	integrations: [(await import("@playform/inline")).default()],
};

Getting started

Critters will now automatically inline the critical CSS of your HTML files.

Default Inlining

You can override any of the default options from the configuration of:

or disable them entirely:

export default {
	integrations: [
		(await import("@playform/inline")).default({
			Critters: false,
		}),
	],
};

Add Multiple Paths

You can add multiple paths to inline by specifying an array as the Path variable.

astro.config.ts

export default {
	integrations: [
		(await import("@playform/inline")).default({
			Path: ["./Target", "./Build"],
		}),
	],
};

Input-Output Mapping

You can also provide a map of paths for different input output directories.

astro.config.ts

export default {
	integrations: [
		(await import("@playform/inline")).default({
			Path: new Map([["./Source", "./Target"]]),
		}),
	],
};

Or an array of the two.

astro.config.ts

export default {
	integrations: [
		(await import("@playform/inline")).default({
			Path: [
				// Inline Target
				"./Target",
				// Inline Target one more time into a different directory
				new Map([["./Target", "./TargetInline"]]),
			],
		}),
	],
};

File Filtering

You can filter files to exclude specific ones from inlining. A filter can be an array of regular expressions or a single match. You can also use functions to match on file names:

astro.config.ts

export default {
	integrations: [
		(await import("@playform/inline")).default({
			Exclude: [
				"File.html",
				(File: string) => File === "./Target/index.html",
			],
		}),
	],
};

Controlling Logging

You can control the logging level by setting the Logger parameter. The default value is 2, but you can set it to 0 if you don't want to see debug messages:

export default {
	integrations: [
		(await import("@playform/inline")).default({
			Logger: 0,
		}),
	],
};

Changelog

See CHANGELOG.md for a history of changes to this integration.

inline's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar nikolarhristov 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

inline's Issues

Need Critters: true to work?

Hi there

I've recently updated to and don't know if this is intended, but critters only started working after defining critters: true on astro config.

"astro": "^2.5.5",
"astro-critters": "^1.1.35",
...
critters({
    critters: true,
    preload: 'body',
  }),
...

also, is it possible to change the preload strategy? i thought we could override any option there.

repo here if you wanna take a look: https://github.com/bronze/carlosbronze-com-br/tree/dev

cheers!

Options currently working?

I have a quick question about astro-critters. (Amazing stuff, BTW.) Is it currently working with the regular options? I have the following within astro.config.mjs:

integrations: [
  sitemap(),
  critters({
    pruneSource: true,
    fonts: true,
  })
]

... but it doesn't seem to respect either of those selections; CSS files aren't being "pruned" and fonts are not being inlined with the critical CSS.

I am using astro-critters 0.0.5 and astro 1.0.0-beta.17. The repo on which I'm doing this is https://github.com/brycewray/astro-site and the resulting website is https://www.brycewray.com. Note: I may take astro-critters offline on the repo and site for a while due to the CLS that's caused by the fonts not being inlined, but I'll do so by only commenting it out so you still can see what I have.

Thanks in advance for any help you might offer.

It keeps processing the same file

Hi and thank you for your work.
I'm running the extension on a fairly large project and i get the following behavior on every file. It seems to me that it outputs the same file again and again. The project has multiple routes and thousands of files and everyone of them in the end contain the same css. I have used your extension in other projects and never had this. Using your latest version, same goes for Astro.
Another weird thing is that it ignores all options. For example:

      critters({
        exclude: [
          (file) => console.log('-------', file)
        ],
      }),

The above code does not output (as you can see on the logs bellow) the console.log. On a brand new small project it does, same package.json on both projects.

The output

Time 146.0939
4 rules skipped due to selector errors:
  .prose :where(hr + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
  .prose :where(h2 + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
  .prose :where(h3 + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
  .prose :where(h4 + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
Inlined 17.3 kB (30% of original 56.1 kB) of _astro/about-us.8647140a.css.
Inlined 82 B (3% of original 2.49 kB) of _astro/_...page_.0f08ca28.css.
Time 159.6
4 rules skipped due to selector errors:
  .prose :where(hr + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
  .prose :where(h2 + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
  .prose :where(h3 + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
  .prose :where(h4 + *):not(:where([class~="not-prose"] *)) -> Cannot read properties of undefined (reading 'type')
Inlined 17.3 kB (30% of original 56.1 kB) of _astro/about-us.8647140a.css.
Inlined 82 B (3% of original 2.49 kB) of _astro/_...page_.0f08ca28.css.

Any ideas?

Original critters options don't have any impact

Hello,

I'm trying to fine tune critters process, but it seems options from original Critters don't have any impact at all.

The configuration file looks like below:

  integrations: [
    critters({
      minimumExternalSize: 1000000,
      keyframes: "all",
      pruneSource: true,
      noscriptFallback: false,
    }),
  ],
});

No one option listed above doesn't have any impact on the final build - builds look identically with or without these options.

Any ideas?

Does not work when base or site config is a subfolder.


import image from '@astrojs/image';

import { fileURLToPath } from 'url';
import path, { dirname } from 'path';
import critters from 'astro-critters';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// https://astro.build/config
export default defineConfig({
    base: '/some/subfolder',
    //site: 'https://somedomain.com/some/subfolder',
    integrations: [
        image({
            serviceEntryPoint: '@astrojs/image/sharp',
            logLevel: 'debug',
            cacheDir: './.cache/image',
        }),
        critters(),
    ],
    vite: {
        resolve: {
            alias: {
                '@/': `${path.resolve(__dirname, 'src')}/`,
            },
        },
        css: {
            devSourcemap: true,
            preprocessorOptions: {
                scss: {
                    additionalData(source, fp) {
                        // All scss files ending with globals/_.scss
                        // will not re-import additionalData
                        if (fp.indexOf('/globals/_') >= 0) return source;
                        // Use additionalData from legacy nuxt scss options
                        return `@import "@/styles/globals/globals"; ${source}`;
                    },
                },
            },
        },
    },
});

Gives this error:
Unable to locate stylesheet: [PATH HIDDEN]/dist/some/subfolder/assets/index.36b57366.css

Critters dont work if the url has a prefix

if you have a build that puts a url in front of the css, this is the assetsPrefix option in astro, you will have this difference

<link rel="stylesheet" href="http://localhost:4321/_astro/index.Bd8XMnIY.css">

<link rel="stylesheet" href="/_astro/index.Bd8XMnIY.css">

and when you have a prefix with the url or domain dont works well, and don't inline nothing

[BUG]: Critical CSS extracted and not removed from styles.css

Hi,

I have this Astro config:

import { defineConfig } from "astro/config";
import tailwind from "@astrojs/tailwind";
import sitemap from "@astrojs/sitemap";
import { loadEnv } from "vite";
import compress from "astro-compress";
import critters from "astro-critters";

const env = loadEnv(import.meta.env.MODE, process.cwd(), "");

// https://astro.build/config
export default defineConfig({
  site: env.SITE_URL,
  integrations: [tailwind(), sitemap(), critters(), compress()],
});

The result of this is that my critterial CSS was extracted to my index.html but that extracted CSS is not removed from my CSS file. However according to the crittiers library this CSS is removed from my CSS file.

Captura de pantalla 2023-03-27 a las 16 52 30

Captura de pantalla 2023-03-27 a las 16 53 43

Thanks for your awesome work!

CSS File Added Twice

Hi there,

<link rel="stylesheet" href="/_astro/a.e72665bf.css" media="print" onload="this.media=&apos;all&apos;"><noscript><link rel="stylesheet" href="/_astro/a.e72665bf.css">

On my critters output, the CSS file is emitted twice. Once with the media="print" and one without.

How can I fix that?

Astro version: 2.6.4
Astro critters: 1.1.38

Passing :root as a selector?

Hi there

I'm trying to pass a :root selector trough astro-critters unsuccessfully (so far).
I have some dark mode settings set with :root[data-theme~='dark'] and I'm trying to get those into the critical css.

:root[data-theme~='dark'] {
  --color-default: 128 0 29;
  --color-primary: 94 129 172;
  ...
}

So far none of these seem to yield the desired result:

 includeSelectors: [/\:root/, /^\:root.*/, /[:]\s*root.*/, /\:root\s*\{([^}]*)\}/, /\:root\[data-theme~=['"][^'"]*['"]\]/, /\:root/, ':root', ':root[data-theme~=\'dark\']'], }

By now I'm just throwing everything and seeing what sticks...

Any ideas?

cheers

Invalid syntax for <link onload='...'/> in Chrome

The generated <link onload='this.media=\' all\''/> throws caught SyntaxError: Invalid or unexpected token (at (index):17:9140) in Chrome.

The temporary fix is to do a string replace:
onload='this.media=\'all\'' -> onload="this.media='all'"

Unable to locate stylesheet after 1.29 update

I haven't changed any of my config files, but critters seems to have added another /blog/ folder while trying to locate css files. here's my astro.config

Screenshot 2023-02-09 at 7 23 32 PM

import { defineConfig } from "astro/config";
import image from "@astrojs/image";
import react from "@astrojs/react";
import critters from "astro-critters";

// https://astro.build/config
import compress from "astro-compress";

// https://astro.build/config
import sitemap from "@astrojs/sitemap";

// https://astro.build/config
export default defineConfig({
  site: "https://www.getguru.com",
  server: {
    hostname: "localhost",
    port: 3000,
  },
  base: "/blog",
  outDir: "./dist/blog",
  integrations: [
    image({
      serviceEntryPoint: "@astrojs/image/sharp",
      logLevel: "debug",
    }),
    react(),
    critters(),
    sitemap(),
  ],
});

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.