Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

405
Vistas
How to use dynamic imports conditionally?

I have a React app created with CRA. The app is built for two environments: website and browser extension which replaces a speed dial. Whereas it is nice to use dynamic imports for website, it would be good to bundle some pages into main chunk, so that there is no splashscreen when opening a new tab.

Do you have any idea how to conditionally use dynamic imports basing on environment variable? I've tried the following approach:

import WebsktopEager from 'pages/app/Websktop';
const WebsktopLazy = lazy(() => import('pages/app/Websktop'));

const Websktop = process.env.REACT_APP_TARGET === 'extension' ? WebsktopEager : WebsktopLazy;

I expected that webpack's tree shaking would remove dead code basing on the condition, but WebsktopEager is still bundled into a main chunk, even though process.env.REACT_APP_TARGET !== 'extension'.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Based on your code, cherry-picked bundling won't happen just because process.env.REACT_APP_TARGET === 'extension' is present as you expected; because it'll only work on runtime!

So CRA will be optimistic while bundling the code, and will bundle eager imports as well.

What you can do is have two separate entry files, of sorts: For eg -

main.eager.js // containing your eager imports
main.lazy.js // containing your dynamic/lazy imports

Now have a custom webpack config to separately build the projects based on any condition, environment variables that you'd like to use. And the entry point for those bundles can be differentiated based on the above said files

But ofcourse custom webpack config would require you to execute npm run eject command. So take a look at articles about that online

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda