Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何从docker和webpack访问react中的环境变量_Reactjs_Docker_Webpack - Fatal编程技术网

Reactjs 如何从docker和webpack访问react中的环境变量

Reactjs 如何从docker和webpack访问react中的环境变量,reactjs,docker,webpack,Reactjs,Docker,Webpack,我有一个react前端应用程序,它是通过webpack构建的,并使用docker进行容器化 目标:能够在docker中定义环境变量,并能够在我的reactjs应用程序中访问环境变量 docker compose.yml version: '3' services: portal: build: context: . dockerfile: Dockerfile environment: - NODE_ENV=production

我有一个react前端应用程序,它是通过webpack构建的,并使用docker进行容器化

目标:能够在docker中定义环境变量,并能够在我的reactjs应用程序中访问环境变量

docker compose.yml

version: '3'

services:
  portal:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - NODE_ENV=production
      - PORT=8080
      - API_URL=http://test.com
    ports:
      - "8080:8080"
例如,我想在我的reactjs应用程序中访问这个
api\uURL
变量

webpack.prod.js

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const WebpackShellPlugin = require('webpack-shell-plugin');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const webpack = require('webpack');
const dotenv = require('dotenv');

console.log(process.env);

module.exports = [{
    entry: {
        app1: ["./src/public/app1/index.tsx"],

    },
    mode: NODE_ENV,
    watch: NODE_ENV === 'development',
    output: {

        filename: "[name]/bundle.js",
        path: path.resolve(__dirname, 'build/public/'),
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json", ".css", ".scss"]
    },

    module: {
        rules: [
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },


            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" },

            { test: /\.scss$/, use: [ 
                { loader: "style-loader" },  // to inject the result into the DOM as a style block
                { loader: "css-loader", options: { modules: true } },  // to convert the resulting CSS to Javascript to be bundled (modules:true to rename CSS classes in output to cryptic identifiers, except if wrapped in a :global(...) pseudo class)
                { loader: "sass-loader" },  // to convert SASS to CSS
            ] }, 
        ]
    },
    "plugins": [
        // new CleanWebpackPlugin(),
        new webpack.DefinePlugin({
            'process.env.API_URL': JSON.stringify(process.env.API_URL)
        }),

        new CopyWebpackPlugin([
            {
                from: "src/public/app1/index.html",
                to: "app1"
            },
        ]),
    ],



    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        // "react": "React",
        // "react-dom": "ReactDOM"
    }
}]
你可以看到我正在用下面的插件在webpack中设置环境变量

   new webpack.DefinePlugin({
                'process.env.API_URL': JSON.stringify(process.env.API_URL)
            }),
问题:您可以看到我的网页配置中有控制台记录的process.env,但没有显示我在docker中设置的任何环境变量

背景:

DockerFile

FROM node:10.16.0-alpine
# Bundle APP files
WORKDIR /app
COPY ./ /app/
# Install app dependencies
ENV NPM_CONFIG_LOGLEVEL warn
RUN npm ci
RUN npm run build
npm

"build": "webpack --config webpack.prod.js",

只有在容器启动时,docker compose.yml文件中的环境变量才可用

如果希望它们在生成期间也可用,则可以使用生成参数:

version: '3'

services:
  portal:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - NODE_ENV=production
        - PORT=8080
        - API_URL=http://test.com
    ports:
      - "8080:8080"
FROM node:10.16.0-alpine

# Build args
ARG NODE_ENV
ARG PORT
ARG API_URL

# Environment vars
ENV NODE_ENV=$NODE_ENV
ENV PORT=$PORT
ENV API_URL=$API_URL

# Bundle APP files
WORKDIR /app
COPY ./ /app/

# Install app dependencies
ENV NPM_CONFIG_LOGLEVEL warn
RUN npm ci
RUN npm run build
然后,在Dockerfile中,使用
ARG
命令声明生成参数,然后声明
ENV
变量,将它们设置为生成参数的值:

version: '3'

services:
  portal:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - NODE_ENV=production
        - PORT=8080
        - API_URL=http://test.com
    ports:
      - "8080:8080"
FROM node:10.16.0-alpine

# Build args
ARG NODE_ENV
ARG PORT
ARG API_URL

# Environment vars
ENV NODE_ENV=$NODE_ENV
ENV PORT=$PORT
ENV API_URL=$API_URL

# Bundle APP files
WORKDIR /app
COPY ./ /app/

# Install app dependencies
ENV NPM_CONFIG_LOGLEVEL warn
RUN npm ci
RUN npm run build

我希望这会有所帮助。

您是否遵循了此处提到的所有步骤?我没有使用create react Apps,但正如您所看到的,我正在执行所有操作。您能否解释一下,为什么您认为args可以工作,而不是环境?谢谢您,这是可行的,但我;我不喜欢在我的dockerfile中定义所有这些参数和环境,尤其是如果你有很多这样的参数和环境的话。你认为用这种方式还是使用.env文件和.env.production文件?