简体   繁体   中英

NextJS/Ant-design styles and JS bundles delaying to load in staging

Hello beautiful people,

I need help with my NextJS and Ant-design app. The present issue is only happening on stagging & production environment, I am not able to reproduce it locally, neither by running:

  • npm run dev
  • nor npm run build and npm run start

Here is the staging link, the issue only happens the first time the page load and when doing hard-refresh.

PROBLEM

I am having a LayoutWrapper component which displays the navbar, the main content, and the footer. In this code below, I am using the useBreakpoint() hook from ant-design for the responsiveness of the navbar. But the first time it is displaying the entire page like on mobile, then after a few seconds, the page returns back to the desktop version. The same issue happens after hard-refreshing the browser.

I realized that some CSS and JS bundles take time to load. Resulting in this behavior.

The layout component looks like this:

const LayoutWrapper: React.FC<Props> = ({
  baseUrl,
  title,
  image,
  description,
  isHome = false,
  isError = false,
  isCause = false,
  isCategory = false,
  isCreate = false,
  noFooter = false,
  isForm = false,
  children,
}) => {
  const { svpProps } = React.useContext(Context);
  const router = useRouter();
  const screens = useBreakpoint();

  const [scrolled, setScrolled] = React.useState("");
  const user = useSelector((state: IRootState) => state.user);

  const dispatch = useDispatch();

  const scrollHandler = () => {
    setScrolled(
      window.pageYOffset > 640
        ? "over"
        : window.pageYOffset > 80
        ? "scrolled"
        : "",
    );
  };

  React.useEffect(() => {
    window.addEventListener("scroll", scrollHandler);
  }, [scrollHandler]);

  React.useEffect(() => {
    if (user.currentUser.isLoggedin && _.isEmpty(user.currentUser.data)) {
      getCurrentUser(dispatch);
    }
  }, [dispatch]);

  const _url = `${getPlatformUrl()}${router.asPath}`;
  const _description = description || "More Than A Crowdfunding Platform";
  const _siteName = "Save Plus";
  const _author = "Exuus";
  const _image = image || `${getPlatformUrl()}/images/get-started.png`;
  const _title = title || "";
  const _twitterHandle = "@SavePlusHQ";

  return (
    <Layout className={styles.layout}>
      <Head>
        {svpProps.error || user.currentUser.error.message ? (
          <title>Error | {_siteName}</title>
        ) : (
          <title>
            {title ? `${_title} | ` : ""}
            {_siteName}
          </title>
        )}
        <link
          href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap"
          rel="stylesheet"
        />
        <link rel="canonical" href={_url} />
        <meta name="description" content={_description} />
        <meta property="og:type" content="website" />
        <meta property="og:site_name" content={_siteName} />
        <meta property="og:title" content={_title} />
        <meta property="og:image" content={_image} />
        <meta property="og:description" content={_description} />
        <meta property="og:url" content={_url} />
        {!isCause && <meta name="twitter:site" content={_twitterHandle} />}
        <meta name="twitter:card" content="summary" />
        <meta name="twitter:title" content={_title} />
        <meta name="twitter:description" content={_description} />
        <meta name="twitter:image" content={_image} />
        <meta name="author" content={_author} />
        <link
          id="favicon"
          rel="shortcut icon"
          href="/icons/favicon-32x32.png"
          sizes="16x16 32x32 48x48"
          type="image/png"
        />
      </Head>
      {screens.lg ? (
        <Header
          scrolled={scrolled}
          isCategory={isCategory}
          user={user}
          isHome={isHome}
          isCreate={isCreate}
          svpProps={svpProps}
          baseUrl={baseUrl}
        />
      ) : (
        <MobileHeader
          scrolled={scrolled}
          isCategory={isCategory}
          user={user}
          isHome={isHome}
          isCreate={isCreate}
          svpProps={svpProps}
          baseUrl={baseUrl}
        />
      )}
      {svpProps.error || user.currentUser.error.message ? (
        <Content className={styles.layout__content} data-is-form="true">
          <Result
            status="500"
            title="Oooops!"
            subTitle={
              <>
                Sorry, something went wrong.
                <br />
                {svpProps.error || user.currentUser.error.message}
              </>
            }
            extra={
              <>
                <Button
                  type="primary"
                  onClick={() => router.push("/")}
                  icon={<HomeOutlined />}
                />
                <Button onClick={() => router.reload()}>RELOAD</Button>
              </>
            }
          />
        </Content>
      ) : (
        <Content
          className={styles.layout__content}
          data-is-category={isCategory}
          data-is-form={isForm}
          data-is-error={isError}
        >
          {children}
        </Content>
      )}
      {!noFooter && (
        <Footer className={styles.layout__footer}>
          <FooterItem />
        </Footer>
      )}
    </Layout>
  );
};

export default LayoutWrapper;

My __app.js file looks like this:

import React from "react";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Router } from "next/router";
import { withRedux } from "helpers/with-redux-store";
import getInitialProps from "helpers/getInitialProps";
import Context from "helpers/context";
import "react-image-crop/dist/ReactCrop.css";

import "theme/index.css";
import "theme/global.scss";
import "styles/global.scss";

Router.events.on("routeChangeStart", () => NProgress.start());
Router.events.on("routeChangeComplete", () => {
  window.scroll({
    top: 0,
    left: 0,
  });
  NProgress.done();
});
Router.events.on("routeChangeError", () => NProgress.done());

const MyApp = ({ Component, pageProps, svpProps }) => {
  return (
    <Context.Provider value={{ svpProps }}>
      <Component {...pageProps} svpProps={svpProps} />
    </Context.Provider>
  );
};

MyApp.getInitialProps = getInitialProps;

export default withRedux(MyApp);

Here is the way I am loading the ant-design styles using LESS

@import '../../node_modules/antd/lib/style/themes/default.less';
@import '../../node_modules/antd/dist/antd.less';
@import './theme.less';

And I have a script that compiles the LESS theme to CSS "build-css": "less-watch-compiler --run-once --enable-js --main-file=index.less theme/less/ theme/",

The result theme/index.css is included in my __app.js as the above snippet shows

I realized this problem since my teammates start using this script to deploy the app

sudo git pull origin develop && sudo yarn install && sudo yarn build && sudo pm2 restart all"

I really don't have any idea on how I can fix this weird bug, as It not happening locally

just try to replace it with react-responsive

export const useResponsive = () => {
  const xxl = useMediaQuery({
    query: "(min-width: 1600px)",
  });
  const xl = useMediaQuery({
    query: "(min-width: 1200px)",
  });
  const lg = useMediaQuery({
    query: "(min-width: 992px)",
  });
  const md = useMediaQuery({
    query: "(min-width: 768px)",
  });
  const sm = useMediaQuery({
    query: "(min-width: 576px)",
  });
  const xs = useMediaQuery({
    query: "(max-width: 576px)",
  });
  return { xxl, xl, lg, md, sm, xs };
};

this hook will solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM