CSS 在第一次加载时损坏,在热重载时得到纠正

CSS is breaking on first load, gets corrected on hot reload

我网站上的

CSS 在第一次构建加载时中断,但当我在代码上按 command + s 时会自动更正。 Hotreload 在这里发挥了作用。

在开发环境中,可以通过更改和 command + s 并撤消相同的操作并再次 command + s 暂时解决此问题。这将触发 hotreload 并最终重新捆绑所有资产(包括 css),并在现场正确加载 css。

但是在暂存或生产中,我们通过生产构建程序, NODE_ENV=production IS_BUILDING_NEXTJS=1 next build src 所以不能在那里破解。

我试过从 webpackConfig 中删除所有别名,但没有用。

下面是我的next.config.js

const withCSS = require("@zeit/next-css");
module.exports = withCSS({
  cssLoaderOptions: {
    url: false
  },
  // NextJS builds to `/src/.next` by default. Change that to `/build/app`
  distDir: "../build/app",
  webpack: (webpackConfig) => {
    webpackConfig.module.rules.push({
      test: /\.(gql|graphql)$/,
      loader: "graphql-tag/loader",
      exclude: ["/node_modules/", "/.next/"],
      enforce: "pre"
    });
    webpackConfig.resolve.alias.handlebars = 'handlebars/dist/handlebars.min.js';
    webpackConfig.module.rules.push({
      test: /\.mjs$/,
      type: "javascript/auto"
    });
    webpackConfig.resolve.alias["styled-components"] = "styled-components/dist/styled-components.browser.esm.js";
    return webpackConfig;
  }
});

预计 css 应在每个环境中的第一次加载时正确加载。

目前,在开发中,它可以在 hotreload 上正确加载。 Hortreload 在 staging/production.

上感觉不对

以下修复有效,这将消除重新渲染问题和 CSS 错误地应用于组件。从 material-ui CSS not working on SSR issue

获得参考

我们需要将 dangerouslyUseGlobalCSS 设置为 true

generateClassName: createGenerateClassName({ dangerouslyUseGlobalCSS: true })

src/getPageContext.js 文件

中的函数 createPageContext()