Print stylesheet in Next.js 10

1.3k Views Asked by At

In my Next 10 application, I can import global styles in _app.js like so

import 'assets/css/app.css'

I'd like to add a print stylesheet. I know I can use a @media print { } query to app.css, but ideally it would be loaded as a separate file so the download priority is lower, e.g.

<link rel="stylesheet" href="/assets/css/print.css" media="print">

Is this possible using Next.js? I can't see any obvious way to control how the actual <link> tag is rendered.

The only way I can see this might work is to have a custom bit of Webpack/file-loader configuration that matches print.css only, which feels... less than ideal.

2

There are 2 best solutions below

1
On

I have the same question as you velvetkevorkian but with the intend to use the following technique:

<link rel="stylesheet" href="webfonts.css" media="print" onload="this.media='all'" />

This will indeed lower the priority in the loading queue, prevent rendering from being blocked and finally replace the native fonts by the webfonts.

UPDATE: not ideal but for my "simple" CSS file (which only defines font-face) here is what I did:

  1. Move my webfonts.css file to the public folder
  2. Manually add my <link> inside <Head>
3
On

Its possible, yes!

You can create Print.module.css in folder pages or anywhere, inside of this file you must use

@media print {
     /* its an example */
    .noPrint{
      display: none;
    }
}

Inside your file .js or .tsx you call this css like a

import print from './Print.module.css'

and call the className like:

className={print.noPrint}

if you have more stylesheets in your project you can differenciate like this:

import print from './Print.module.css'
import styles from './General.module.css'

and call the classes together, it goes like this:

className={`${styles.anyclass} ${print.anyclass}`}

this works too for responsive stylesheets, enough follow this logic with respectives media queries.