简体   繁体   English

如何有条件地使用动态导入?

[英]How to use dynamic imports conditionally?

I have a React app created with CRA.我有一个用 CRA 创建的 React 应用程序。 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' .我预计 webpack 的树抖动会根据条件删除死代码,但WebsktopEager仍然捆绑到一个主块中,即使process.env.REACT_APP_TARGET !== 'extension'

Based on your code, cherry-picked bundling won't happen just because process.env.REACT_APP_TARGET === 'extension' is present as you expected;根据您的代码,不会仅仅因为process.env.REACT_APP_TARGET === 'extension'如您预期的那样存在而进行精心挑选的捆绑; because it'll only work on runtime!因为它只能在运行时工作!

So CRA will be optimistic while bundling the code, and will bundle eager imports as well.因此,CRA 在捆绑代码时会保持乐观,并且也会捆绑急切的导入。

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.现在有一个自定义的 webpack 配置,可以根据您想要使用的任何条件、环境变量单独构建项目。 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.但是当然自定义 webpack 配置需要你执行npm run eject runeject 命令。 So take a look at articles about that online所以看看网上关于那个的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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