如何在NextJS项目的head标签中内联CSS? [英] How to inline CSS in the head tag of a NextJS project?

查看:491
本文介绍了如何在NextJS项目的head标签中内联CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的NextJS项目具有以下Webpack配置:

My NextJS project has the following Webpack configuration:

import path from 'path';
import glob from 'glob';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import webpack from 'webpack';
import dotenv from 'dotenv';
import OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin';

import withSass from '@zeit/next-sass';

dotenv.config();

module.exports = withSass({
  distDir: '.build',
  webpack: (config, { dev, isServer }) => {
    if (isServer) {
      return config;
    }
    config.plugins.push(
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 1,
      }),
    );
    config.optimization.minimizer.push(
      new OptimizeCSSAssetsPlugin({}),
    );
    return config;
  },
});

这使我可以在任何页面中导入任意数量的scss文件,并将它们捆绑在一起,缩小为一个文件,并按以下方式投放:

This allows me to just import any number of scss files in any page and have them all bundled together, minified as a single file, and served thus:

<link rel="stylesheet" href="/_next/static/css/styles.84a02761.chunk.css">

但是,我非常希望将样式定义内联为<style></style>,而不是<link>.是否可以不堆积大量的第三方模块?

However, instead of <link>, I'd very much prefer to have the style definitions inlined into my <head> tag as <style></style>. Is it possible without piling up a ton of third-party modules?

如果没有,是否有可能至少将结果<link>relstylesheet更改为preload,并在其中添加添加as="style" crossorigin?

If not, is it possible to at least change the resulting <link>'s rel to preload from stylesheet and also add add as="style" crossorigin to it?

推荐答案

通过稍微调整pages/_document.jsx文件,我成功地成功内联了CSS.我扩展了 NextJS 本机提供的<Head>组件,并将其添加到我的自定义文档标记中.这是我所做修改的部分表示:

I managed to successfully inline my CSS by slightly tweaking the pages/_document.jsx file. I extended the <Head> component natively provided with NextJS and added it to my custom document markup. Here's a partial representation of my modifications:

import { readFileSync } from 'fs';
import { join } from 'path';

class InlineStylesHead extends Head {
  getCssLinks() {
    return this.__getInlineStyles();
  }

  __getInlineStyles() {
    const { assetPrefix, files } = this.context._documentProps;
    if (!files || files.length === 0) return null;

    return files.filter(file => /\.css$/.test(file)).map(file => (
      <style
        key={file}
        data-href={`${assetPrefix}/_next/${file}`}
        dangerouslySetInnerHTML={{
          __html: readFileSync(join(process.cwd(), '.build', file), 'utf-8'),
        }}
      />
    ));
  }
}

class MyDocument extends Document {
  render() {
    return (
      <Html lang="en" dir="ltr">
        <InlineStylesHead>
          <meta name="theme-color" content="#ffcc66" />
        </InlineStylesHead>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

我将此解决方案归功于 https://github.com/zeit /next-plugins/issues/238#issuecomment-432211871 .

I owe this solution to https://github.com/zeit/next-plugins/issues/238#issuecomment-432211871.

这篇关于如何在NextJS项目的head标签中内联CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆