¿Por qué mi aplicación Shopify creada con Next.js (React) se carga tan lentamente?

Aug 15 2020

Seguí este tutorial:https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react

Desde el principio, mi aplicación tardó mucho en cargarse, incluso cuando cambiaba de pestaña, incluso cuando se cargaba a través de ngrok y se ejecutaba en localhost o se implementaba en el motor de la aplicación.

¿Qué podría estar causando esto?

PD: Soy nuevo en el desarrollo de aplicaciones React, Next.js y Shopify, por lo que la respuesta podría ser bastante básica.

PPS: el resultado de la compilación parece indicar que "First Load JS shared by all" es demasiado grande según el color rojo. No sé cómo investigar esto y reducir el tamaño de dichos fragmentos, aunque solo 214 KB no podrían explicar tiempos de carga tan lentos, ¿o sí?


Construir


Perfilador de herramientas React Dev


Salida @next/bundle-analyzer:

analizado

comprimido


paquete.json

 {
      "name": "ShopifyApp1",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "dev": "node server.js NODE_ENV=dev",
        "build": "next build",
        "deploy": "next build && gcloud app deploy --version=deploy",
        "start": "NODE_ENV=production node server.js",
        "analyze": "cross-env ANALYZE=true npm run build"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "@google-cloud/storage": "^5.2.0",
        "@next/bundle-analyzer": "^9.5.2",
        "@sendgrid/mail": "^7.2.3",
        "@shopify/app-bridge-react": "^1.26.2",
        "@shopify/koa-shopify-auth": "^3.1.65",
        "@shopify/koa-shopify-graphql-proxy": "^4.0.1",
        "@shopify/koa-shopify-webhooks": "^2.4.3",
        "@shopify/polaris": "^5.1.0",
        "@zeit/next-css": "^1.0.1",
        "apollo-boost": "^0.4.9",
        "cors": "^2.8.5",
        "cross-env": "^7.0.2",
        "dotenv": "^8.2.0",
        "email-validator": "^2.0.4",
        "extract-domain": "^2.2.1",
        "firebase-admin": "^9.0.0",
        "graphql": "^15.3.0",
        "helmet": "^4.0.0",
        "isomorphic-fetch": "^2.2.1",
        "js-cookie": "^2.2.1",
        "koa": "^2.13.0",
        "koa-body": "^4.2.0",
        "koa-bodyparser": "^4.3.0",
        "koa-helmet": "^5.2.0",
        "koa-router": "^9.1.0",
        "koa-session": "^6.0.0",
        "next": "^9.5.1",
        "react": "^16.13.1",
        "react-apollo": "^3.1.5",
        "react-dom": "^16.13.1",
        "react-infinite-scroll-component": "^5.0.5",
        "sanitize-html": "^1.27.2",
        "scheduler": "^0.19.1",
        "store-js": "^2.0.4",
        "tldts": "^5.6.46"
      },
      "devDependencies": {
        "webpack-bundle-analyzer": "^3.8.0",
        "webpack-bundle-size-analyzer": "^3.1.0"
      },
      "browser": {
        "@google-cloud/storage": false,
        "@sendgrid/mail": false,
        "@shopify/koa-shopify-auth": false,
        "@shopify/koa-shopify-graphql-proxy": false,
        "@shopify/koa-shopify-webhooks": false,
        "cors": false,
        "email-validator": false,
        "extract-domain": false,
        "firebase-admin": false,
        "graphql": false,
        "helmet": false,
        "isomorphic-fetch": false,
        "koa": false,
        "koa-body": false,
        "koa-bodyparser": false,
        "koa-helmet": false,
        "koa-router": false,
        "koa-session": false,
        "sanitize-html": false,
        "tldts": false
      }
    }

Pestaña Red de herramientas de desarrollo de Chrome

EDITAR:

npm run dev

Por alguna razón, el tiempo de carga de la línea "webpack-hmr" sigue aumentando constantemente.

npm run build && npm run start


siguiente.config.js

require("dotenv").config({path:"live.env"});
const withCSS = require('@zeit/next-css');
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const withBundleAnalyzer = require('@next/bundle-analyzer')({enabled: process.env.ANALYZE === 'true'})
const apiKey =  JSON.stringify(process.env.SHOPIFY_API_KEY);
module.exports =  withBundleAnalyzer(
  withCSS({
    distDir: 'build',
    webpack: (config) => {
      const env = { API_KEY: apiKey };
      config.plugins.push(new webpack.DefinePlugin(env));
      config.plugins.push(new webpack.DefinePlugin(new BundleAnalyzerPlugin()));
      config.resolve = {
        alias: {
          'react-dom$': 'react-dom/profiling',
          'scheduler/tracing': 'scheduler/tracing-profiling'
        },
        ...config.resolve
      };
      return config;
    }
  })
);

_app.js

import App from 'next/app';
import Head from 'next/head';
import { AppProvider } from '@shopify/polaris';
import { Provider } from '@shopify/app-bridge-react';
import '@shopify/polaris/dist/styles.css'
import translations from '@shopify/polaris/locales/en.json';
import Cookies from 'js-cookie';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';

const client = new ApolloClient({
  fetchOptions: {
    credentials: 'include'
  },
});

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    const config = { apiKey: API_KEY, shopOrigin: Cookies.get("shopOrigin"), forceRedirect: true };
    return (
      <React.Fragment>
        <Head>
          <title>...</title>
          <meta charSet="utf-8" />
        </Head>
        <Provider config={config}>
          <AppProvider i18n={translations}>
            <ApolloProvider client={client}>
              <Component {...pageProps} />
            </ApolloProvider>
          </AppProvider>
        </Provider>
      </React.Fragment>
    );
  }
}

export default MyApp;

Index.js (cliente)

import {
  Button,
  Card,
  Form,
  FormLayout,
  Layout,
  Page,
  Stack,
  TextField,
  DisplayText,
  Toast,
  Frame
} from '@shopify/polaris';

class Index extends React.Component  {

  state = {
    emails: '',
    domain: '' ,
    alias: '',
    err: '',
    message: '',
    active: false,
    loadingDomainResponse: false,
    loadingEmailResponse: false
  };

  componentDidMount() {
    fetch(`/state`, {
      method: 'GET'
    }).then(response => response.json())
    .then(result => {
      if (result.err) {
        this.setState({
          err: result.err,
          message: result.err,
          active: true
        })
      }
      else {
        this.setState({
          emails: result.emails,
          domain: result.domain,
          alias: result.alias
        })
      }
    });
  };

  

  render() {

    const { emails, domain, alias, err, message, active, loadingEmailResponse, loadingDomainResponse} = this.state;
    

    const toastMarkup = active ? (
      <Toast content={message} error={err} onDismiss={this.handleToast}/> 
    ) : null;


    return (
      <Frame>
         <Page>
          {toastMarkup}
          <Layout>
            <Layout.AnnotatedSection
              title="..."
              description="..."
            >
              <Card sectioned>
                <Form onSubmit={this.handleSubmitEmails}>
                  <FormLayout>
                    <TextField
                      value={emails}
                      onChange={this.handleChange('emails')}
                      label="..."
                      type="emails"
                      maxlength="200"
                    />
                    <Stack distribution="trailing">
                      <Button primary submit loading={loadingEmailResponse}>
                        Save
                      </Button>
                    </Stack>
                  </FormLayout>
                </Form>
              </Card>
            </Layout.AnnotatedSection>
            <Layout.AnnotatedSection
              title="..."
              description="..."
            >
              <Card sectioned>
                <DisplayText size="small"> {domain} </DisplayText>
                <br/>
                <Form onSubmit={this.handleSubmitDomain}>
                  <FormLayout>
                    <TextField
                      value={alias}
                      onChange={this.handleChange('alias')}
                      label="..."
                      type="text"
                      maxlength="50"
                    />
                    <Stack distribution="trailing">
                      <Button primary submit loading={loadingDomainResponse}>
                        Save
                      </Button>
                    </Stack>
                  </FormLayout>
                </Form>
              </Card>
            </Layout.AnnotatedSection>
          </Layout> 
       </Page>
      </Frame>
    );
  }

  handleToast = () => {
    this.setState({
      err: false,
      message: false,
      active: false
    })
  };
  
  handleSubmitEmails = () => {
    this.setState({loadingEmailResponse:true});
    fetch(`/emails`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        emails: this.state.emails
      })
    }).then(response => response.json())
    .then(result => {
      console.log("JSON: "+JSON.stringify(result));
      if (result.err) {
        this.setState({
          err: result.err,
          message: result.err,
          active: true
        })
      }
      else {
        this.setState({message: "...", active: true});
      }
      this.setState({loadingEmailResponse:false});
    });
  };

  handleSubmitDomain = () => {
    this.setState({loadingDomainResponse:true});
    fetch(`/domain`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: 
        JSON.stringify({
          alias: this.state.alias
        })
      }).then(response => response.json())
      .then(result => {
        console.log("JSON: "+JSON.stringify(result));
        if (result.err) {
          this.setState({
            err: result.err,
            message: result.err,
            active: true
          })
        }
        else {
          this.setState({message: "...", active: true});
        }
        this.setState({loadingDomainResponse:false});
      });
  };

  


  handleChange = (field) => {
    return (value) => this.setState({ [field]: value });
  };
}

export default Index;

servidor.js

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
app.prepare().then(() => {
    const server = new Koa();
    const router = new Router();
    server.use(bodyParser());
    server.use(session({ secure: true, sameSite: 'none' }, server));
    server.keys = [SHOPIFY_API_SECRET_KEY];
    router.get('/state',  async (ctx) => {
        let domain = ctx.session.shop;
        let alias;
        const snap = await global.db.collection("...").doc(ctx.session.shop).get();
            if (snap.data().alias) {
                alias = snap.data().alias;
            }
            let emails = snap.data().emails;
            let emailString = "";
            if (!emails) {
                ctx.response.body = {err: "..."};
            }
            else if(emails.length < 4) {
                for (email of emails) {
                    emailString += (","+email);
                }
                theEmailString = emailString.substring(1);
                let response = {
                    domain: domain,
                    alias: alias,
                    emails: theEmailString
                }
                ctx.response.body = response;
            } 
            else {
                ctx.response.body = {err: "..."};
            }
    });
});

Editar

He proporcionado una respuesta inicial, pero estoy buscando una mejor si es posible.

Además, parece posible hacer que los enlaces de navegación del puente de la aplicación Shopify usen el enrutador next.js en lugar de activar recargas de página completa:

https://shopify.dev/tools/app-bridge/actions/navigation

Si alguien comparte cómo hacer eso para next.js con suficiente detalle, sería mejor que mi respuesta.

Respuestas

Xandor Aug 15 2020 at 23:48

Su carga inicial en el índice, de acuerdo con la cascada de herramientas de desarrollo, tomó casi 2 segundos para solo 18,5 KB de datos. Esto es alarmantemente lento y antes de que se alcance el resto de sus recursos. Mi primer pensamiento sería el retraso de la red/servidor. ¿Está alojando esto localmente o en un servidor web de algún tipo?

Lo reduciría tanto como pueda, tal vez incluso intente cargar un archivo index.html simple con solo un encabezado. Si tarda un par de segundos en cargarse, es posible que deba actualizar o migrar a un mejor host. Si está alojando localmente, esto podría ser solo un problema de que su Internet tiene una baja velocidad de carga. Muchos planes de Internet tienen descargas rápidas pero cargas lentas y no siempre obtendrás lo que promete tu ISP.

LandryPlacid Aug 16 2020 at 20:11

intente optimizar su código eliminando cualquier código innecesario. Trate de usar una importación más dinámica de modo que obtenga una carga inicial rápida de placa de bioler y los códigos pesados ​​como cuadros, gráficos e imágenes y carga de video en un momento posterior en el extremo del cliente. import dynamic from "next/dynamic", esto debería darle al cliente una primera vista de pintura rápida como lo hace youtube.

https://nextjs.org/docs/advanced-features/dynamic-import

pruebe reaccionar Formik (un controlador de formulario optimizado para aplicaciones pequeñas) y también intente usar componentes de función sobre componentes de clase. Con Next puede realizar la mayoría de sus llamadas a la base de datos en getStatiProps, getServerSideProps, getStaticPaths. para la recuperación periódica en caché, use el gancho SWR.

TheProgrammer Aug 22 2020 at 21:37

Compartí los tiempos de carga medidos usando npm run dev en mi pregunta, pero aquí también hay información sobre los tiempos de carga en el modo de producción.

Ejecutar la aplicación en modo producción ( npm run buildy npm run start) después de quitar la incrustación en la interfaz de usuario de administración de Shopify muestra que la aplicación tarda un total de aproximadamente 2 segundos en cargarse en modo producción, lo que todavía parece muy lento (la interfaz de usuario de Shopify estaba agregando alrededor de 3 segundos).

Los enlaces de navegación de la novia de la aplicación Shopify recargarían la página completa cuando se hiciera clic en ellos en lugar de cambiar de página como lo harían los enlaces de Next.js.

Se reemplazaron los enlaces de Navegación de la aplicación con los enlaces Siguiente.

Aún así, 1,86 segundos para la primera carga es muy lento y estoy abierto a mejores soluciones.