如何在webpack配置文件中访问运行时环境变量

fjnneemd  于 2023-10-19  发布在  Webpack
关注(0)|答案(1)|浏览(161)

我试图在配置了Webpack 5和ModuleFederation插件的Docker容器内运行create react应用程序。我想一次构建应用程序,然后在多个环境中部署,每个环境都加载相应的远程。所以我在docker运行期间传入env变量,如下所示
用于说明docker run -d -p 3000:8080 -e REACT_APP_DEPLOY_ENV=dev my-app
我的webpack配置(react-app-rewired)

webpack(config, env) {
        if (env === 'development') {
            config.plugins.push(
                new ModuleFederationPlugin({
                    name: 'my-app',
                    filename: 'remoteEntry.js',
                    remotes: {
                        remoteApp: "remoteApp@http://localhost:8888/remoteEntry.js"
                    },
                    exposes: {
                    },
                    shared: {
                        ...deps,
                        react: {
                            singleton: true,
                            requiredVersion: deps.react,
                        },
                        'react-dom': {
                            singleton: true,
                            requiredVersion: deps['react-dom'],
                        },
                    },
                })
            );
        } else {
            const env = process.env.REACT_APP_DEPLOY_ENV
            config.plugins.push(
                new ModuleFederationPlugin({
                    name: 'my-app',
                    filename: 'remoteEntry.js',
                    remotes: {
                        remoteApp: `remoteApp@https://myapp-${env}.com/remoteEntry.js`
                    },
                    exposes: {
                    },
                    shared: {
                        ...deps,
                        react: {
                            singleton: true,
                            requiredVersion: deps.react,
                        },
                        'react-dom': {
                            singleton: true,
                            requiredVersion: deps['react-dom'],
                        },
                    },
                })
            );
            config.plugins.push(
                new DefinePlugin({
                    'process.env.REACT_APP_DEPLOY_ENV': JSON.stringify(
                        process.env.REACT_APP_DEPLOY_ENV || 'dev'
                    ),
                })
            );
        }
        return config;
    },
};

但是我无法在webpack配置中访问REACT_APP_DEPLOY_ENV。env是undefined。当我执行到我的容器中并执行printenv时,我看到REACT_APP_DEPLOY_ENV=dev。如何在我的moduleFederation插件中访问此变量以动态加载我的远程URL。有人能帮帮我吗?

hjzp0vay

hjzp0vay1#

new webpack.DefinePlugin({
  'process.env' : process.env
})

它可能会解决你的问题

相关问题