React CRA 构建时间变量问题 - 多条目解决方法

时间:2021-01-07 14:37:21

标签: reactjs create-react-app

我正在尝试使用 react 和 create-react-app 根据使用动态导入的环境变量来选择构建目标。这是我想要完成的:

const BUILD_TARGETS : ITarget[] = [
  {
    name: "app",
    path: "./modules/app/Index",
  },
  {
    name: "admin",
    path: "./modules/admin/Index",
  },
];


// Determine which entry point to import
const target = BUILD_TARGETS.find(c=>process.env.REACT_APP_BUILD_TARGET === c.name) as ITarget;

//Import the entry point and render it's default export
import(`${target.path}`).then(({ default: BuildTarget }) =>
  ReactDOM.render(
   
    <>
    <BuildTarget />
  
    </>
      ,
    document.getElementById("root")
  )
);

我已经尝试通过多种方式设置 REACT_APP_BUILD_TARGET,如此处引用的 CRA Environment Variables,但是,似乎存在一些潜在问题,即构建了两个模块并且来自两个模块的代码都包含在最终构建资产中。如果我像下面那样直接指定模块路径,则会构建正确的模块并排除另一个模块的代码:

    import("./modules/app/Index").then(({ default: BuildTarget }) =>
  ReactDOM.render(
    
    <>
    <BuildTarget />
  
    </>
      ,
    document.getElementById("root")
  )
);

CRA 中是否存在阻止 react-scripts 访问入口文件中的环境变量的限制?

解决方法: 这并没有回答我为什么上述不起作用的问题,但我已经确定了一种解决方法。在运行 react-scripts start/build 命令之前,我正在编写脚本并复制入口文件。在我的例子中,我正在执行一个 powershell 脚本,如下所示:

"build-app": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./build.ps1 src\\app.index.tsx build",
"build-admin": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./build.ps1 src\\admin.index.tsx build",
"start-app": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./build.ps1 src\\app.index.tsx start",
"start-admin": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./build.ps1 src\\admin.index.tsx start"

build.ps1

$module=$args[0]
$script=$args[1]
Copy-Item $module -Destination "src/index.tsx"
npm run-script $script

0 个答案:

没有答案