[英]create environment variables based on the webpack entry point
I am splitting my react code with multiple entry points in webpack, these bundles are then loaded independently at completely different pages(HTML documents).我将我的反应代码与 webpack 中的多个入口点分开,然后这些包在完全不同的页面(HTML 文档)中独立加载。
I have a lot of shared code, and most of my shared logic is under if-else
check, so this shared logic is present in all the bundles, causing the increase in bundle size.我有很多共享代码,我的大部分共享逻辑都在if-else
检查下,所以这个共享逻辑存在于所有 bundle 中,导致 bundle 大小增加。 The condition for this if-else
check is based on a variable which we generate at run time, but these variables can be set based on the entrypoint.此if-else
检查的条件基于我们在运行时生成的变量,但这些变量可以根据入口点进行设置。
Is it possible to set some environment variable based on entrypoints(which I can use for the if-else
check), so webpack can treeshake and remove the code which is not required in the bundle?是否可以根据入口点设置一些环境变量(我可以将其用于if-else
检查),所以 webpack 可以 treeshake 并删除捆绑包中不需要的代码吗?
I had a more less similar issue on my project.我的项目中有一个不太相似的问题。 We needed to have different builds for different products and of course wanted to omit irrelevant code in the bundle.我们需要针对不同的产品进行不同的构建,当然希望在捆绑包中省略不相关的代码。 Might be you find something useful here也许你在这里找到了有用的东西
{
scripts: {
"build:first": "SET TYPE=first && npm run build",
"build:second": "SET TYPE=second && npm run build"
}
}
Note - I am using SET SOME_VARIABLE=XXXX
to provide environment variable for the build注意 - 我正在使用SET SOME_VARIABLE=XXXX
为构建提供环境变量
/shared/first.tsx /共享/first.tsx
export const firstMethod = () => "I AM A FIRST";
/shared/second.tsx /共享/second.tsx
export const secondMethod = () => "I AM A SECOND";
// first.tsx // 第一个.tsx
import { firstMethod } from "./shared/first";
export default () => <> First Component says: {firstMethod()} </>;
// second.tsx // 第二个.tsx
import { secondMethod } from "./shared/second";
export default () => <> Second Component says: {secondMethod()} </>;
let LazyComponent: React.LazyExoticComponent<() => JSX.Element>;
if (process.env.TYPE === "first") {
LazyComponent = React.lazy(() => import("./first"));
} else {
LazyComponent = React.lazy(() => import("./second"));
}
class App extends Component {
render() { return <LazyComponent />; }
}
Now, if you run npm run build:first
and check the bundle you will see that:现在,如果您运行npm run build:first
并检查包,您将看到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.